解决方法:
// 保存当前第一个可见的item的索引和偏移量int index = mList.getFirstVisiblePosition();View v = mList.getChildAt(0);int top = (v == null) ? 0 : v.getTop();// ...//根据上次保存的index和偏移量恢复上次的位置mList.setSelectionFromTop(index, top);
这里使用了setSelectionFromTop来ListView。其实还可以使用setSelection也可以定位,只是setSelectionFromTop要比setSelection更精准。因为通过getFirstVisiblePosition
得到的第一个item可能已经有一部分是不可见的了,如果用setSelection无法反映出这不可见的部分。
来看一个自己写的列子:
MainActivity.java:
public class MainActivity extends Activity { private ListView lv_lists; private Button mBtn_show; private Button mBtn_save; private LinearLayout mLl_show; private int index; // 保存上一次列表索引 private int top; // 保存上一次Y轴设置的偏移量 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mLl_show = (LinearLayout) findViewById(R.id.ll_show); lv_lists = (ListView) findViewById(R.id.lv_lists); lv_lists.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, getData())); lv_lists.setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // TODO Auto-generated method stub // Log.d("TAG", "XIXI->" + scrollState); switch (scrollState) { case 0: mLl_show.setVisibility(View.VISIBLE); break; default: mLl_show.setVisibility(View.GONE); break; } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // TODO Auto-generated method stub // Log.d("TAG",view.getId()+", "+firstVisibleItem+", "+visibleItemCount+", "+totalItemCount); } }); mBtn_show = (Button) findViewById(R.id.btn_show); mBtn_show.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub lv_lists.setSelectionFromTop(index, top); } }); mBtn_save = (Button) findViewById(R.id.btn_save); mBtn_save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub index = lv_lists.getFirstVisiblePosition(); View v1 = lv_lists.getChildAt(0); top = (v1 == null) ? 0 : v1.getTop(); // Log.d("TAG",index+", "+top+","); } }); } private String[] getData() { // TODO Auto-generated method stub String temp[] = new String[100]; for (int i = 0; i < temp.length; i++) { temp[i] = "我是第" + i + "个选项"; } return temp; }}
activity_main.xml: