user2847219
user2847219

Reputation: 555

Android listview getView checkBox

Something strange is happening, when I click a row in the list the corresponding checkbox is also selected. So everything is right, but the strange thing is that, automatically every 7 rows the checkbox setcheked to true. What's the problem? Thanks for your help

 ListAdapter adapter = new ArrayAdapter<Dettaglio1>
            (this, R.layout.deteails_list_pdf, R.id.tv_nome_categoria, dettagli1) {
 @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View row = super.getView(position, convertView, parent);
...
...
 list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    final Dettaglio1 d1 = dettagli1.get(position);

                    d1.setChecked(!d1.isChecked());

                    CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox2);
                    checkBox.setChecked(d1.isChecked());

                }
            });
            return row;
        }
    };
    list.setAdapter(adapter);

private class Dettaglio1 {
    String nome;

    private boolean isChecked;

    public void setChecked(boolean isChecked) {
        this.isChecked = isChecked;
    }

    public boolean isChecked() {
        return isChecked;
    }
}

Upvotes: 0

Views: 287

Answers (1)

npace
npace

Reputation: 4258

What's happening is known as view recycling - the core mechanism behind ListView and RecyclerView. Every 7th CheckBox is checked, because that's the same CheckBox recycled and displayed with its previous state.

To fix your problem, you need to keep the 'checked' state inside your data model (the Dettaglio1 class). For example, you can modify your data model like so:

public class Dettaglio1 {
    // stuff
    private boolean isChecked;

    public void setChecked(boolean isChecked) {
        this.isChecked = isChecked;
    }

    public void isChecked() {
        return isChecked;
    }
    // more stuff
}

And your listener like so:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    final Dettaglio1 d1 = dettagli1.get(position);
    d1.setChecked(!d1.isChecked());

    CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox2);
    checkBox.setChecked(d1.isChecked());
}

Edit: You also need to override your adapter's getView() method and set the CheckBox's checked state according to the Dettaglio1 at the current position.

Upvotes: 1

Related Questions