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


更多相关文章

  1. android 定义 程序 Scheme 接收特定URI开启Activity
  2. Android-Service组件之AIDL
  3. android 开发工具相关
  4. Git和Repo扫盲——如何取得Android源代码
  5. Android(安卓)Wifi 启动过程分析
  6. Android(安卓)+ Axis2
  7. Android(安卓)8.1.0 SystemUI 修改之 - 系统锁屏状态下点击用户
  8. Android应用升级构想和要点总结
  9. [ZZ][Android]使用bindService启动服务

随机推荐

  1. android中dp和px的转换
  2. Android 应用软件开发(八)窗口布局
  3. Does Android Support Dual-Cores or Mul
  4. 通过ijetty获取android设备的截图
  5. Android 增量更新实例(Smart App Updates)
  6. Android 数据存储之SQLite数据库
  7. Android -- ContentProvider
  8. Android客户端与服务端通信乱码问题的解
  9. [置顶] 我的Android进阶之旅------>andro
  10. Retrofit简单使用(Kotlin)