简体   繁体   中英

Fragment ListView with Checkbox strange behavior

I have a ListView with Checkbox inside a Fragment that extends FragmentList . The strange behavior is multiple items get checked when one item is clicked. Strangely, when the list is scrolled, some item gets automatically selected or deselected and I have no ScrollListener set.

Here's the code :

@Override
public void onStart() {
    super.onStart();
    getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            CheckBox mCheckBox = (CheckBox) view.findViewById(R.id.chk);
            if (mCheckBox.isChecked()) {
                mCheckBox.setChecked(false);
                getListView().setItemChecked(i, false);
            } else {
                mCheckBox.setChecked(true);
                getListView().setItemChecked(i, true);
            }
            mCallback.onArticleSelected(i, isChoice);
        }
    });
}

Required: image http://windrealm.org/tutorials/android/planets-fragmentactivity.png

ListView 's items recycle while you are scrolling. You should put a boolean parameter (isChecked) to your ListView row object then in your getView method u should initialize your CheckBox with that boolean parameter. For example:

Assume that your row object:

public class Trial{

    public String title;

    public boolean isChecked;

}

In your ListView adapter's getView method, you should check isChecked parameter of your object:

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    LayoutInflater inflater = ((Activity) context).getLayoutInflater();
    View view = inflater.inflate(R.layout.your_listview_item, parent, false);

    Trial item = items.get(position);

    yourHolder.checkBox = (CheckBox) view.findViewById(R.id.chk);
    yourHolder.checkBox.setChecked(item.isChecked);

    return view;
}

Good luck.

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