user874747
user874747

Reputation:

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.

Upvotes: 2

Views: 1563

Answers (3)

Praveen Kumar
Praveen Kumar

Reputation: 26

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.

Upvotes: 1

dac2009
dac2009

Reputation: 3561

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.

Upvotes: 3

Nikola Despotoski
Nikola Despotoski

Reputation: 50578

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

Upvotes: 2

Related Questions