Toggle checkbox programmatically
Asked Answered
T

6

20

I have a ListView of items that need to be checkable/uncheckable. I have set up an ArrayAdapter that is currently using android.R.layout.simple_list_item_multiple_choice as the row, and everything displays just fine. I am also able to properly get the clicks on this item. However, the Checkbox in the UI does not toggle when the item is selected. I've been trying to figure this out for a while, can anyone point me in the right direction? I just want to know how to force the UI to update to reflect the changed state of the checkbox.

I can provide code if needed, but I'm trying to look for something very specific here, so I figure posting a bunch of my code wouldn't be of much help.

Thanks!

Talya answered 9/11, 2011 at 6:45 Comment(0)
J
30

First of all go through my this answer: Android listview with check boxes?

Nice as you want to implement checked/unchecked check boxes in ListView, you just need to implement below lines in getView() method:

 // also check this lines in the above example
ViewHolder holder = (ViewHolder) view.getTag();
holder.checkbox.setChecked(list.get(position).isSelected());

Also check the getView() method for the implementation of event on CheckBox residing inside the ListView:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = null;
    if (convertView == null) {
        LayoutInflater inflator = context.getLayoutInflater();
        view = inflator.inflate(R.layout.rowbuttonlayout, null);
        final ViewHolder viewHolder = new ViewHolder();
        viewHolder.text = (TextView) view.findViewById(R.id.label);
        viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);
        viewHolder.checkbox
            .setOnCheckedChangeListener(
                new CompoundButton.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView,
                        boolean isChecked) {
                    Model element = (Model) viewHolder.checkbox
                            .getTag();
                    element.setSelected(buttonView.isChecked());
                }
            });
        view.setTag(viewHolder);
        viewHolder.checkbox.setTag(list.get(position));
    } else {
        view = convertView;
        ((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
    }
    ViewHolder holder = (ViewHolder) view.getTag();
    holder.text.setText(list.get(position).getName());
    holder.checkbox.setChecked(list.get(position).isSelected());
    // ......  
}
Janeejaneen answered 9/11, 2011 at 6:52 Comment(6)
+1 i am your follower,can you please tell me what to do (read/watch) to know more about android as you do.! thanks..learnt a lot from your answers.Massotherapy
Thanx for the kind words. I am always trying to learn a topic for a day and doing SO and my blog. what else require to learn new topic :) , Where are you from?Janeejaneen
India, I also do the thing come to SO and find atleast one topic i dont know and get the question and answer about that..but still sometime i got bored/tired of doing that..but you guys keep encouraging me.Massotherapy
Thanks for your reply! So you're saying neither the base ListView class nor the base ArrayAdapter will work for the purpose of getting checkboxes to work?Talya
ArrayAdapter can also work, check this example vogella.de/articles/AndroidListView/article.htmlJaneejaneen
@PareshMayani do you have any idea how to make this to work with single checkbox selection ? I tried everything and it doesn't seem to work. The closest I got was to manually clear all the selection states from the custom items, but it only worked for the rows above my selection, the ones bellow required a second click to work.Greenwich
B
36

Programmatically in java code

CheckBox mCheckBox = (CheckBox) findViewById(R.id.checkBox);

mCheckBox.setChecked(true); //to check
mCheckBox.setChecked(false); //to uncheck

In android XML

android:checked="true" //to check
android:checked="false" //to uncheck

as

<CheckBox
    android:id="@+id/checkBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="true"
    android:text="Checkbox Item" />
Beckett answered 26/5, 2014 at 9:46 Comment(0)
J
30

First of all go through my this answer: Android listview with check boxes?

Nice as you want to implement checked/unchecked check boxes in ListView, you just need to implement below lines in getView() method:

 // also check this lines in the above example
ViewHolder holder = (ViewHolder) view.getTag();
holder.checkbox.setChecked(list.get(position).isSelected());

Also check the getView() method for the implementation of event on CheckBox residing inside the ListView:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = null;
    if (convertView == null) {
        LayoutInflater inflator = context.getLayoutInflater();
        view = inflator.inflate(R.layout.rowbuttonlayout, null);
        final ViewHolder viewHolder = new ViewHolder();
        viewHolder.text = (TextView) view.findViewById(R.id.label);
        viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);
        viewHolder.checkbox
            .setOnCheckedChangeListener(
                new CompoundButton.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView,
                        boolean isChecked) {
                    Model element = (Model) viewHolder.checkbox
                            .getTag();
                    element.setSelected(buttonView.isChecked());
                }
            });
        view.setTag(viewHolder);
        viewHolder.checkbox.setTag(list.get(position));
    } else {
        view = convertView;
        ((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
    }
    ViewHolder holder = (ViewHolder) view.getTag();
    holder.text.setText(list.get(position).getName());
    holder.checkbox.setChecked(list.get(position).isSelected());
    // ......  
}
Janeejaneen answered 9/11, 2011 at 6:52 Comment(6)
+1 i am your follower,can you please tell me what to do (read/watch) to know more about android as you do.! thanks..learnt a lot from your answers.Massotherapy
Thanx for the kind words. I am always trying to learn a topic for a day and doing SO and my blog. what else require to learn new topic :) , Where are you from?Janeejaneen
India, I also do the thing come to SO and find atleast one topic i dont know and get the question and answer about that..but still sometime i got bored/tired of doing that..but you guys keep encouraging me.Massotherapy
Thanks for your reply! So you're saying neither the base ListView class nor the base ArrayAdapter will work for the purpose of getting checkboxes to work?Talya
ArrayAdapter can also work, check this example vogella.de/articles/AndroidListView/article.htmlJaneejaneen
@PareshMayani do you have any idea how to make this to work with single checkbox selection ? I tried everything and it doesn't seem to work. The closest I got was to manually clear all the selection states from the custom items, but it only worked for the rows above my selection, the ones bellow required a second click to work.Greenwich
G
4

Have you tried the following?

@Override
public void onListItemClick(ListView listView, View view, int position, long id) {

    //Invert the checkbox-status        
    ((CheckedTextView) view.findViewById(R.id.text1)).setChecked(!isChecked());

    return;

}   
Girosol answered 9/11, 2011 at 6:51 Comment(2)
The items in the list are dynamic--there's no unique XML ID for every row item. Unless I've got my understanding of that wrong? But I tried it anyway, and got a NullPointerException :(Talya
In any case, you don't need to do that, you can do checkbox.toggle() ;)Triparted
K
2

In kotlin, set the checkbox unchecked programmatically

binding.imageCheckBox.post { binding.imageCheckBox.setChecked(false) }

and set the checkbox checked programmatically

binding.imageCheckBox.post { binding.imageCheckBox.setChecked(true) }
Knisley answered 24/1, 2022 at 8:29 Comment(1)
This is exactly what I need, it helped me out.Tinder
H
0

You can use a custom base adapter. This will allow you to choose only one at at time, but you may change this by undoing the check to see which ones are selected.

public class CheckBoxGridAdapter extends BaseAdapter{

    LayoutInflater inflater;
    ArrayList<Holder> list;
    int res;
    Context context;

    public CheckBoxGridAdapter(Context context, ArrayList<Holder> list, int layoutResourceId) {
        inflater = LayoutInflater.from(context);
        this.context = context;
        this.list =list;
        this.res = layoutResourceId;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View convertView, ViewGroup parent) { 
        final ViewHolder holder; 
        if (convertView == null) { 
            convertView = inflater.inflate(res, 
                    parent, false);
            holder = new ViewHolder(); 
            holder.tv1 = (TextView) convertView.findViewById(R.id.checkBoxTxt); 
            holder.cb = (CheckBox) convertView.findViewById(R.id.checkBox); 
           convertView.setTag(holder); 
       } else { 
           holder = (ViewHolder) convertView.getTag(); 
       } 
       Holder h = list.get(position);
       holder.tv1.setText(h.getCBName());
       holder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

           @Override
           public void onCheckedChanged(CompoundButton buttonView,
                   boolean isChecked) {
               if(isChecked)
               {
                    int pos = (Integer) buttonView.getTag();
                    checkChecks(pos);               
               }
               CheckBoxGridAdapter.this.notifyDataSetChanged();
           }
       });
       holder.cb.setTag(position);
       holder.cb.setChecked(list.get(position).getSelectState());
       return convertView; 
    }

    protected void checkChecks(int pos) {
            for(int i = 0;i<list.size();i++)
            {
                Holder h = (Holder) list.get(i);
                if(i==pos)
                {
                  Log.d( pos +" checked","is checked");
                  h.setSelectState(true);
                }
                else
                {
                     Log.d( i +" checked","is  not checked");
                     h.setSelectState(false);
                }
            }
    }

    static class ViewHolder
    {
        TextView tv1;
        CheckBox cb;
        RadioButton rb;
    }

}
Headless answered 2/7, 2014 at 6:15 Comment(0)
N
0

You can toggle the checkbox by doing this:

checkbox.setChecked(!checkbox.isChecked());

Where checkbox is your "Checkbox" element.

Narcotism answered 30/1, 2021 at 15:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.