Note that there are some explanatory texts on larger screens.

plurals
  1. POStoring CheckBox state in a ListView
    text
    copied!<p>I'm trying to implement a piece of code I found to store the state of a <code>CheckBox</code> that is in a <code>ListView</code> but it didn't worked. Does anyone have any idea why my code from my adapter isn't working?</p> <pre><code>package kevin.erica.box; import java.util.ArrayList; import kevin.erica.box.R; import android.R.color; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; public class MobileArrayAdapter extends ArrayAdapter&lt;String&gt; { private final Context context; private final String[] values; private ArrayList&lt;Boolean&gt; itemChecked = new ArrayList&lt;Boolean&gt;(); public MobileArrayAdapter(Context context, String[] values) { super(context, R.layout.list_adapter, values); this.context = context; this.values = values; for (int i = 0; i &lt; this.getCount(); i++) { itemChecked.add(i, false); // initializes all items value with false } } @Override public View getView(final int position, View covertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rowView = inflater.inflate(R.layout.list_adapter, parent, false); CheckBox textView = (CheckBox) rowView.findViewById(R.id.checkBox1); textView.setTextColor(0xFFFFFFFF); textView.setText(values[position]); //Store state attempt final CheckBox cBox = (CheckBox) rowView.findViewById(R.id.checkBox1); // your // CheckBox cBox.setOnClickListener(new OnClickListener() { public void onClick(View v) { CheckBox cb = (CheckBox) v.findViewById(R.id.checkBox1); if (cb.isChecked()) { itemChecked.set(position, true); // do some operations here } else if (!cb.isChecked()) { itemChecked.set(position, false); // do some operations here } } }); cBox.setChecked(itemChecked.get(position)); // this will Check or Uncheck the // CheckBox in ListView // according to their original // position and CheckBox never // loss his State when you // Scroll the List Items. return rowView; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload