0

我有一个带有列表片段的活动,其中有一个布局,每行都有一个复选框。我onclick为复选框设置 xml 属性并执行以下测试

public void onBoxClick(View v){
    checkedItems = listview.getCheckedItemPositions();
    int checkedItemsCount = checkedItems.size();

}

checkedItemsCount回来0,我想得到你使用的被检查的项目,listview.getCheckedItemPositions()但事实并非如此,我怎么知道列表中检查了什么?

这是我的列表片段创作

@Override
    public void onActivityCreated(Bundle state){
        super.onActivityCreated(state);
        listview = getListView();
        listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        listview.setItemsCanFocus(false);
        setEmptyText("No Bowlers");       
        registerForContextMenu(getListView());
        populateList();
    }
4

2 回答 2

0

这篇文章可能会有所帮助。它使用 custom 提供了一个解决方案,它为每一行ResourceCursorAdapter提供 aCheckBox和 a 。TextViewListView

要选择多个项目ListView,请检查此页面。请注意,该示例使用 aListActivity而不是 a ListFragment,但您的代码最终会非常相似。只需确保您Fragment正确实现了生命周期方法(即在ListFragment's中设置 AdapteronActivityCreated()等)。

于 2012-01-16T18:18:13.830 回答
0

我通过自定义适配器解决了这个问题bindView,我创建了一个ArrayList<Integer>变量

ArrayList<Integer> mCheckedItems = new ArrayList<Integer>();

并在bindViewcheckedchangelistener在复选框上设置一个以查看该框是否被选中。如果它被选中,我将光标进入的数据库中的 id 放入mCheckedItems Array

适配器:

public class CheckAdapter extends SimpleCursorAdapter{

    Context context;

    public CheckAdapter(Context context, int layout, Cursor c,String[] from, int[] to,int flag) {
        super(context, layout, c, from, to);
        this.context = context;
    }

    @Override
    public void bindView(View view,Context context,Cursor cursor){
        final String name = cursor.getString(cursor.getColumnIndex(BowlersDB.NAME));
        final int id = cursor.getInt(cursor.getColumnIndex(BowlersDB.ID));
        TextView tv = (TextView)view.findViewById(R.id.nameCheckTV);
        tv.setText(name);

        CheckBox cb = (CheckBox)view.findViewById(R.id.checkBox1);
        cb.setOnCheckedChangeListener(new OnCheckedChangeListener(){

            @Override
            public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {

                if(isChecked){
                    mCheckedItems.add(id);
                }else if(!isChecked){
                    for(int i=0; i< mCheckedItems.size(); i++){
                        if(mCheckedItems.get(i) == id){
                            mCheckedItems.remove(i);
                        }
                    }                   
                }

            }

        });
    }

将 id 插入数组后,我使用数组列表按照我的需要使用它们

于 2012-01-18T04:26:37.537 回答