简体   繁体   中英

Listview and checkbox problem Android Studio

I am using a SQLite database for an android studio application and I am using a ListView to display data. I recently put a CheckBox (without adding anything in the database) and the problem I have is that when I check a box and go down in the ListView (I specify that it does me when II have a lot of item in the list) my box is unchecked or either boxes are randomly checked.

here is my code in Adapter:

 @Override public View getView(int i, View view, ViewGroup viewGroup) { //déclaration d"un horlder final ViewHolder holder; // si la ligne n'existe pas encor if(view == null) { holder = new ViewHolder(); // la ligne est construite avec un formatage (inflater) relié à layoutlistpremierp view = inflater.inflate(R.layout.layoutlistsacview, null); //chaque propriété du holder est relié a une propriété graphique holder.checksac = (CheckBox) view.findViewById(R.id.checksac); // affceter le holder à la vue view.setTag(holder); }else{ //récup du holder dans la ligne existante holder = (ViewHolder) view.getTag(); } // valorisation du contenu du holder (donc de la ligne) holder.checksac.setText(LesAjoutSac.get(i).getObjetSac()); return view; } private class ViewHolder{ CheckBox checksac; }

how can i fix it?

You need to keep a list with the data for each row that will save the status of the checkbox, and on the adapter you mark checkbox.isChecked = list[position].isChecked You then need to add a listener to the chceckBox to mark the data in the list list[position]..isChecked = isChecked //isChecked comed from the listener

You can see my example here , but it uses a recyclerView (which I highly recommend over a listView!)

Add this in your adapter:

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

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

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

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