超簡單的listview單選模式SingleMode(自訂listview item),listviewsinglemode

來源:互聯網
上載者:User

超簡單的listview單選模式SingleMode(自訂listview item),listviewsinglemode

來源: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;}@Overridepublic 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;            }        }    }



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.