来源:https://stackoverflow.com/questions/8337180/custom-single-choice-listview/12823457#12823457


1.在listview item里面设置

<span style="font-size:18px;"><RadioButton
     android:id="@+id/radio1"
     android:checked="false"
     android:focusable="false"
     android:clickable="false"
 /></span>

把checked focusable clickable设置为false


2.设置ListView

<ListView
    android:id="@android:id/list"
    android:choiceMode="singleChoice"
    android:descendantFocusability="beforeDescendants"
/>

3.在自定义adapter里面设置

int selectedIndex = -1;

public void setSelectedIndex(int index){
    selectedIndex = index;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    RadioButton rbSelect = (RadioButton) convertView
                        .findViewById(R.id.radio1);
    if(selectedIndex == position){
    rbSelect.setChecked(true);
    }
    else{
    rbSelect.setChecked(false);
    }
}

4.在activity设置list的onItemClickListener

 mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mChangeAdapter.setSelectedIndex(position);
                mChangeAdapter.notifyDataSetChanged();
            }
        });


5.可选,存储单选状态在数据库,第二次打开依然把选中的item给设置为选中状态

 ChangeBean bean = mData.get(position);
        mHolder.tv_name.setText(bean.name);

        if (selectedIndex == position) {
            mHolder.iv_choice.setChecked(true);
            bean.setCheck(true);
            updateData(bean);
        } else {
            mHolder.iv_choice.setChecked(false);
            bean.setCheck(false);
            updateData(bean);
        }

然后在activity中在setAdapter之前把选中的item设置为选中状态
   mChangeAdapter = new ChangeAdapter(this);
        mList.setAdapter(mChangeAdapter);
        initSelect();
        mChangeAdapter.refresh(mDatas);
        addListener();
    }

    private void initSelect() {
        for (int i = 0; i < mDatas.size(); i++)
        {
            if (mDatas.get(i).check){
                mChangeAdapter.setSelectedIndex(i);
                return;
            }
        }
    }



posted on 2015-04-18 13:18  纯洁的坏蛋  阅读(629)  评论(0编辑  收藏  举报