Custom Listview with CheckBox single selection

后端 未结 2 493
臣服心动
臣服心动 2020-12-11 10:17

Here I am creating custom listview with checkbox / RadioButton. I got this but I need the single selection for that.

I try using this lstvw.setChoiceMode(ListV

2条回答
  •  生来不讨喜
    2020-12-11 10:32

    Here is what i would do if i need to select only single item at a time.

    Home.java (Activity)

    package com.lvcheck.activities;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.ListView;
    
    public class Home extends Activity 
    {
        private ListView lvCheckBox;
        private Button btnCheckAll, btnClearALl;
        private String[] arr = {"One", "Two", "Three", "Four", "Five", "Six"};
    
        @Override
        public void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            btnCheckAll = (Button)findViewById(R.id.btnCheckAll);
            btnClearALl = (Button)findViewById(R.id.btnClearAll);
    
            lvCheckBox = (ListView)findViewById(R.id.lvCheckBox);
            lvCheckBox.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            lvCheckBox.setAdapter(new ArrayAdapter(this,
                    android.R.layout.simple_list_item_multiple_choice, arr));
    
    
            btnCheckAll.setOnClickListener(new OnClickListener() 
            {           
                @Override
                public void onClick(View arg0) 
                {
                    for(int i=0 ; i < lvCheckBox.getAdapter().getCount(); i++)
                    {
                        lvCheckBox.setItemChecked(i, true);             
                    }
                }
            });
    
            btnClearALl.setOnClickListener(new OnClickListener() 
            {           
                @Override
                public void onClick(View v) 
                {
                    for(int i=0 ; i < lvCheckBox.getAdapter().getCount(); i++)
                    {
                        lvCheckBox.setItemChecked(i, false);                
                    }
                }
            });
        }
    }
    

    and my (main.xml) XML file should like this

    
    
    
        
    
            
            
        
    
        
        
    
    

    so the output will be like this way..

    enter image description here

    Source: here

    let me know if you have any trouble regarding this.

    Edit: check this useful link: Custom Single choice ListView

提交回复
热议问题