为什么ListView的setSelection无效了?
2015-12-22 18:04 指针空间 阅读(2348) 评论(0) 编辑 收藏 举报官方文档的描述,
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?!!!你确定?!好像并不是这样
ListView的setSelection无效主要原因:
原因一:界面初始化完成之后listview失去了焦点。
原因二:因为listview的item高度不一致,或者添加了headerview,在setadapter之后调用setSelection无法准确定位。
万能解决方法:
- final ListView listView = new ListView(getActivity());
- listView.post(new Runnable() {
- @Override
- public void run() {
- listView.requestFocusFromTouch();//获取焦点
- listView.setSelection(listView.getHeaderViewsCount()+10);
- }
- });
如果还不行,没关系
- final ListView listView = new ListView(getActivity());
- listView.postDelayed(new Runnable() {
- @Override
- public void run() {
- listView.requestFocusFromTouch();
- listView.setSelection(listView.getHeaderViewsCount()+10);
- }
- },500);