0

这是我的问题:我有一个带有自定义 ArrayAdapter 的 ListView:

我的清单onCreate()

list = /*some list*/
listView = (ListView) findViewById(R.id.some_list);
listView.setAdapter(new MapListAdapter(this, R.layout.custom_list_item, list));
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);

listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        listView.setItemChecked(position, true);
    }
});

mapListView.setMultiChoiceModeListener(new MultiChoiceModeListener() {

    @Override
    public boolean onPrepareActionMode(...) {
        // some unrelated working code 
    }

    @Override
    public void onDestroyActionMode(...) {
        // some unrelated working code  
    }

    @Override
    public boolean onCreateActionMode(...) {
        // some unrelated working code 
    }

    @Override
    public boolean onActionItemClicked(...) {
        // some unrelated working code 
    }

    @Override
    public void onItemCheckedStateChanged(...) {
        // some unrelated working code 
    }
});

我的自定义 ArrayAdapter 的getView(...)

@Override
public View getView (int position, View view, ViewGroup parent) {
    view = (LinearLayout) inflater.inflate(layoutId, null);

    final ListItem entry = getItem(position);

    // setting some textviews here and so on...

    CheckBox checkBox = (CheckBox) view.findViewById(R.id.m_l_i_checkbox);
    // my problem ^

    return view;
}

我知道选择了某些列表项,因为 ActionMode 栏在我选择它们时出现,在我取消选择(切换)所有它们时消失。但是,我希望有复选框来指示它们是否确实被选中。那么我该怎么做呢?它适用于 android.R.single_list_item_multiple_choice 和默认 ArrayAdapter,但我想使用我的自定义。也许我弄错了,还有另一种方法可以做到吗?

4

1 回答 1

2

我通过在名为 isSelectedOnList (Boolean) 的 Item 类中添加一个“特殊”字段来实现类似行为的自定义适配器。然后在 OnItemClickListener 我这样做:

listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    mapListView.setItemChecked(position, true);
    ...Get your item here...getItem(position).setIsSelectedOnList(!getItem(position).isSelectedOnList());
}
});

所以现在我的 Items Array 知道选择了哪些项目。然后在 getView 方法中,我更新项目布局 xml 中的复选框:

@Override
public View getView (int position, View view, ViewGroup parent) {
    view = (LinearLayout) inflater.inflate(layoutId, null);

    final ListItem entry = getItem(position);

    // setting some textviews here and so on...

    CheckBox checkBox = (CheckBox) view.findViewById(R.id.m_l_i_checkbox);
    // my problem ^

    checkBox.setChecked(ListItem.isSelectedOnList());

    return view;
}

这个解决方案对我来说效果很好,所以我不想在 android 的内部机制中查看多选列表中的选定项目。

希望这可以帮助...

于 2013-06-24T20:04:11.870 回答