«

android的listview中setselection()不起作用的解决方案

时间:2024-3-2 19:34     作者:韩俊     分类: Android


android的listview中setselection()不起作用的解决方案


遇到一个很诡异的问题,ListView数据没有更改之前,setselection()方法调用效果一切正常;而填充数据更改之后,同样的代码片段却莫名其妙无效了。

先列出搜索到网上的解决方法:


来源:http://stackoverflow.com/questions/1446373/android-listview-setselection-does-not-seem-to-work

1,

ListView.setItemChecked(int position, boolean checked);

Ensure that the listview is set to CHOICE_MODE_SINGLE in the layout XML or in the java via: myList.setChoiceMode(ListView.CHOICE_MODE_SINGLE); and the setItemChecked worked for me, it moved the selection indicator to the item I passed in (unselecting the previous one)


2,

You might need to wrap setSelection() in a posted Runnable (reference).

mListView.clearFocus();
mListView.post(new Runnable() { 
    @Override 
    public void run() {
     mListView.setSelection(index); 
    }
});

很可惜,这两个方法都无法解决我的问题。


最后终于找到了一个解决方案,真是可以形容之为简单粗暴...

上链接,https://code.google.com/p/android/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars&groupby=&sort=&id=6741

摘自19楼

One workaround that fix it without side effects is to set the list adapter again on the list before calling setSelection():

adapter.notifyDataSetChanged();
...

list.setAdapter(adapter);  // or  list.setAdapter(list.getAdapter())
list.setPosition(...);

即直接在调用setSelection 之前重新调用一次setAdapter()就可以了。


回头查官方文档的描述,

public void setSelection (int position) Added in API level 1

Sets the currently selected item. If in touch mode, the item will not be selected but it will still be positioned appropriately. If the specified selection position is less than 0, then the item at position 0 will be selected.

真是悲愤交加,still be positioned appropriately?!!!你确定?!

看看issue页纵横四年时间了这个问题依旧存在╮(╯▽╰)╭希望下个版本还是下下个版本还是下下下个版本能修复吧

标签: android

热门推荐