开发者

CheckBox with SimpleCursorAdapter in ListActivity (ListView)

Hey all, I know there are a number of tutorials of implementing a custom adapter, but I am not convinced that this is right for me. I have a list view of a custom item layout consisting of two TextViews and a CheckBox. I have the following code:

list.setOnItemClickListener(new OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> adapter, View view, int position,
                long rowid) {

            CheckBox c = (CheckBox) view.findViewById(R.id.item_chkbox);
            c.setChecked(!c.isChecked());
            String n = ((TextView) view.findViewById(R.id.item_charName)).getText().toString();
            String 开发者_Go百科p = ((TextView) view.findViewById(R.id.item_playerName)).getText().toString();
            ...

When I tap on an item in the list, a check box is fired and is checked, but it's not the right one. It's not random, either. The CheckBox that is fired is always on the opposite side, mirrored at the center of the list. For example, if I had a list of:

0 1 2 3 4

And tapped "0", 4's check would fire. If I tapped 1, 3's check would fire. If I tap 2, 2's check fires. Even stranger, if I tap 0 twice, 3 checks, then 0 checks. Tap a third time, 3 unchecks. A forth - 0 unchecks. This continues in pattern with all cases. I can't quite figure out what is going on.

Please note that the strings n and p both come out correctly. In other words, tapping 0 would retrieve the string for "name" in the corresponding list item. It's only the CheckBoxes which are out of whack. Any ideas?


I have met your problem, and my solution is removing all things that relative to multiple choice of your list view, such that android:CHOICE_MODE_MULTIPLE, android:choiceMode,.... Just try it!


The blame should go to ListView because when you scroll the custom ListView you should override the getView(...) of the adapter. API docs say the view is recycled. As a result, the state of the previous view should be saved. For example, whether the CheckBox is checked. If you restore the state, ListView will show as expected.


I didn't try, but I think this should work: in onItemClick method, instead of using view object to find the CheckBox, try using ListView.getChildAt(position).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜