码迷,mamicode.com
首页 > 其他好文 > 详细

超简单的listview单选模式SingleMode(自定义listview item)

时间:2015-04-18 14:37:42      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:listview   radiobutton   单选模式   singlechoice   

来源: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;
            }
        }
    }



超简单的listview单选模式SingleMode(自定义listview item)

标签:listview   radiobutton   单选模式   singlechoice   

原文地址:http://blog.csdn.net/qq634416025/article/details/45112539

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!