代码改变世界

为什么ListView的setSelection无效了?

2015-12-22 18:04  指针空间  阅读(2338)  评论(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无法准确定位。

万能解决方法:

 

[java] view plaincopy
 
  1. final ListView listView = new ListView(getActivity());  
  2. listView.post(new Runnable() {  
  3.     @Override  
  4.     public void run() {  
  5.         listView.requestFocusFromTouch();//获取焦点  
  6.          listView.setSelection(listView.getHeaderViewsCount()+10);  
  7.     }  
  8. });  

如果还不行,没关系

 

 

 

 

[java] view plaincopy
 
  1. final ListView listView = new ListView(getActivity());  
  2. listView.postDelayed(new Runnable() {  
  3.     @Override  
  4.     public void run() {  
  5.         listView.requestFocusFromTouch();  
  6.         listView.setSelection(listView.getHeaderViewsCount()+10);  
  7.     }  
  8. },500);