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

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


1.在listview item里面设置


把checked focusable clickable设置为false


2.设置ListView


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;
            }
        }
    }



转载于:https://www.cnblogs.com/tqj-zyy/p/4559745.html

你可能感兴趣的:(超简单的listview单选模式SingleMode(自定义listview item))