简体   繁体   中英

android : checkbox problem?

I'm trying to select all the checkbox in list. Why am getting particular checkbox only true. Code is : -

            ListView listview = (ListView)findViewById(R.id.listview1);
        for(int i=0; i < listview.getChildCount(); i++)
        {
            AbsoluteLayout itemLayout = (AbsoluteLayout)listview.getChildAt(i);
            CheckBox cb = (CheckBox)itemLayout.findViewById(R.id.checkBox1);
            if(cb.isChecked())
            {
                cb.setChecked(false);
            }
            else
            {
                cb.setChecked(true);
            }
        }

Thanks in Advance.

Not sure I understand the question fully..

But I belive:

CheckBox cb = (CheckBox)itemLayout.findViewById(R.id.checkBox1);

will always return the same CheckBox (the one with id checkBox1), even if you have multiple checkboxes in your list.

Try:

   for(int i=0; i < listview.getChildCount(); i++)
        {
            CheckBox cb = (CheckBox)listview.getChildAt(i).findViewById(R.id.checkBox1);  //if the child views are properly populated in each row item then on this particular positon ChBox will be found and instantiated
            if(cb.isChecked())
            {
                cb.setChecked(false);
            }
            else
            {
                cb.setChecked(true);
            }
        }

You Can use this with two buttons like selectall & unselectall

    public void checkallbtn_Click(View view)
{
    ListView lv = (ListView)findViewById(R.id.backuplist);
    CheckBox cb;
    try
    {
        for(int i=0;i<lv.getCount();i++)
        {
            cb = (CheckBox)lv.getChildAt(i).findViewById(R.id.checkBox1);
            if(!cb.isChecked())
            {
                cb.setChecked(true);
            }
        }

    }catch(Exception e) {e.printStackTrace();}
}
public void uncheckallbtn_Click(View view)
{
    ListView lv = (ListView)findViewById(R.id.backuplist);
    try
    {
        for(int i=0;i<lv.getCount();i++)
        {
            CheckBox cb = (CheckBox)lv.getChildAt(i).findViewById(R.id.checkBox1);
            if(cb.isChecked())
            {
                cb.setChecked(false);
            }
        }           
    }catch(Exception e) 
    {
        e.printStackTrace();
    }
}

Hope this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM