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)
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頁縱橫四年時間了這個問題依舊存在╮(╯▽╰)╭希望下個版本還是下下個版本還是下下下個版本能修復吧