Android ListView with checkbox for single-selection

Source: Internet
Author: User

This should be a frequently encountered demand, online to find a lot of demo feel said a little too long so that their own time to record, at present I realize the ListView with checkbox is mainly used in two methods 1, with a bean record state, Each time getview to determine the state of the Bean 2, the click of the position is consistent with GetView position, this approach is less coupling is not recommended: The 1th method: The first is our bean:
 Public  class Bean {    Private BooleanisChecked;PrivateString msg ="This is a test data"; Public Bean(){    } Public Bean(Booleanischeched) { This. isChecked = ischeched; } Public Boolean isChecked() {returnisChecked; } Public void setchecked(BooleanisChecked) { This. isChecked = isChecked; } PublicStringgetmsg() {returnMsg } Public void setmsg(String msg) { This. msg = msg; } }

And then judge the state when GetView.

 PublicViewGetView(intPosition, View Convertview, ViewGroup parent) {Viewholder mviewholder;if(Convertview = =NULL) {Convertview = Minfater.inflate (R.layout.list_item,NULL); Mviewholder =NewViewholder (Convertview);        Convertview.settag (Mviewholder); }Else{Mviewholder = (Viewholder) convertview.gettag (); } mViewHolder.mTextView.setText (Mdatas.get (position). getmsg ());if(Mdatas.get (position). isChecked ()) {//Status checkMViewHolder.mCheckBox.setChecked (true); }Else{mViewHolder.mCheckBox.setChecked (false); }returnConvertview; }
This way we can control whether the checkbox is selected or not by the state of the bean, but the operation is the key when Onitemclick.
 Public  class mainactivity extends actionbaractivity {    PrivateListView Mlistview;PrivateListAdapter Madapter;PrivateList<bean> Mdatas;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        Mlistview = (ListView) Findviewbyid (R.id.main_listview); Mdatas =NewArraylist<bean> (); for(inti =0; I < -; i++) {if(i = =0){//default check FirstMdatas.add (NewBean (true));Continue; } mdatas.add (NewBean (false)); } Madapter =NewListAdapter ( This, Mdatas);        Mlistview.setadapter (Madapter);    Mlistview.setonitemclicklistener (Monitemclicklistener); }Private FinalOnitemclicklistener Monitemclicklistener =NewOnitemclicklistener () {@Override         Public void Onitemclick(adapterview<?> Adapterview, view view,intPositionLongARG3) { for(Bean Bean:mdatas) {//All set to uncheckedBean.setchecked (false); } mdatas.get (position). setchecked (true);//Click Set to selectMadapter.notifydatasetchanged (); }    };}
Xml
<?xml version= "1.0" encoding= "Utf-8"?><linearlayout  xmlns: Android  = "http://schemas.android.com/apk/res/android"  android:layout_width  =" match_parent " android:layout_height  =" match_parent " android:orientation  =;     <TextViewandroid:id="@+id/main_list_item_text"android:layout_width= "0DP" android:layout_height="Match_parent"android:textcolor="@android: Color/black"  android:layout_weight="1"android:gravity="center_vertical" / >                                                     <!--checkbox Get event priority is greater than ListView so set focusable = false--    <CheckBox         Android:id="@+id/main_list_item_checkbox"        Android:layout_width="Wrap_content"        Android:layout_height="Wrap_content"        android:layout_gravity="Center_vertical"        Android:backgroundtintmode="Multiply"        Android:layout_marginright="10DP"          android:clickable="false"        Android:focusableintouchmode="false"        android:focusable="false"/></linearlayout>
So the checkbox of the ListView can be achieved by selecting the second type:

This method is not recommended for use

 Public  class mainactivity extends actionbaractivity {    PrivateListView Mlistview;PrivateListAdapter Madapter;PrivateList<bean> Mdatas; Public Static intPos//Record the selected position    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        Mlistview = (ListView) Findviewbyid (R.id.main_listview); Mdatas =NewArraylist<bean> (); for(inti =0; I < -; i++) {if(i = =0) {Mdatas.add (NewBean (true));Continue; } mdatas.add (NewBean (false)); } Madapter =NewListAdapter ( This, Mdatas);        Mlistview.setadapter (Madapter);    Mlistview.setonitemclicklistener (Monitemclicklistener); }Private FinalOnitemclicklistener Monitemclicklistener =NewOnitemclicklistener () {@Override         Public void Onitemclick(adapterview<?> Adapterview, view view,intPositionLongARG3) {pos = position;        Madapter.notifydatasetchanged (); }    };}
GetView to determine whether mainactivity pos equals getview position
    @Override     PublicViewGetView(intPosition, View Convertview, ViewGroup parent) {Viewholder mviewholder;if(Convertview = =NULL) {Convertview = Minfater.inflate (R.layout.list_item,NULL); Mviewholder =NewViewholder (Convertview);        Convertview.settag (Mviewholder); }Else{Mviewholder = (Viewholder) convertview.gettag (); } mViewHolder.mTextView.setText (Mdatas.get (position). getmsg ());if(Mainactivity.pos = = position) {//mainactivity Pos is equal to positionMViewHolder.mCheckBox.setChecked (true); }Else{mViewHolder.mCheckBox.setChecked (false); }returnConvertview; }
It is not recommended to use the second approach, which makes the program's coupling very low, and the global variable always has a handle to the class object pointing to it unless the class object is to be recycled otherwise the static variable will not be taken out of the GC the above is only personal usage, of course there are other ways to achieve, see personal preferences

Android ListView with checkbox for single-selection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.