以编程方式在ListView中设置激活的项目

时间:2014-01-21 08:43:39

标签: android listview

我有一个简单的ListView,其中一些项目setChoiceMode设置为ListView.CHOICE_MODE_SINGLE,这意味着当我触摸某个项目时,它会突出显示。这样,用户可以看到选择了哪个菜单选项(ListView是菜单):

listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

但是,我想从代码中更改选择(而不是通过触摸)。我试过这个:

listView.setSelection(0);

但它似乎没有效果。可能因为选择和激活是不同的概念。没有setActivated(int)方法可供使用。

3 个答案:

答案 0 :(得分:19)

您可以使用以下代码选择项目:

listView.setItemChecked(position, true);

答案 1 :(得分:1)

使用这种方法对我有用

listView.performItemClick(listView, position, listView.getItemIdAtPosition(position));

答案 2 :(得分:0)

文档说If in touch mode, the item will not be selected but it will still be positioned appropriately

因此,您需要使用ListView.setItemChecked(int position, boolean checked)方法listView.setItemChecked(position, true)将位置设置为选中

相关问题