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

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页纵横四年时间了这个问题依旧存在╮(╯▽╰)╭希望下个版本还是下下个版本还是下下下个版本能修复吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值