Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android listview with check boxes?

I am developing an application which uses list view with check-boxes,consider there are 10 items on list-view items,And by default in that check boxes are checked,Until now every thing is working fine for me here is my problem,When I uncheck any check-box in list-view whole list-view need to be refresh.

like image 924
NikhilReddy Avatar asked Nov 09 '11 04:11

NikhilReddy


1 Answers

Nikhil just keep in mind that defining a custom adapter is one time practice, once you define and understand it properly then you can customize any views like ListView, GridView, Gallery, Spinner. So go through the below answer properly.

For defining ListView with CheckBox (or any View), you have to define your own custom adapter. For defining custom adapter, follow below steps:

  1. Define a custom row file (which represents every items of your listview)
  2. Define a adapter class and extends BaseAdapter.
  3. Inflate the above row xml file inside the getView() method of this adapter class.

In your case,

1st step: (Define row xml file)

<RelativeLayout>
   <TextView>
   <CheckBox>
</RelativeLayout>

2nd & 3rd step: (Define custom adapter class)

public class MyListViewAdapter extends BaseAdapter
{
  ....
  ....


   static class ViewHolder {
        protected TextView text;
        protected CheckBox checkbox;
    }

    @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());


.......
.......
}
like image 178
Paresh Mayani Avatar answered Nov 05 '22 12:11

Paresh Mayani