listview记住上次滑动的位置
第一种:记录listView滚动到的位置的坐标
scrolledX=listview.getScrollX();
scrolledY=listview.getScrolly();
恢复位置时调用:listview.scrollTo(scrolledX,scrolledY);
(但是不知道为什么一直得到的是0,0)
第二种:记录listView显示在屏幕上的第一个item的位置
listView.setOnScrollListener(new OnScrollListener() {
/**
* 滚动状态改变时调用
*/
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// 不滚动时保存当前滚动到的位置
if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
position = listView.getFirstVisiblePosition();
}
}
/**
* 滚动时调用
*/
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
在恢复位置时调用
listView.setSelection(position);
(亲测可以使用)
下面是一个小demo:
package com.example.cklistview;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
ListView listView;
int position;
SharedPreferences sp;
SharedPreferences.Editor mEditor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
mEditor = sp.edit();
position = sp.getInt("list_pos", 0);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_expandable_list_item_1, getData());
listView.setAdapter(arrayAdapter);
listView.setSelection(position);
listView.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView arg0, int arg1) {
// TODO Auto-generated method stub
// 不滚动时保存当前滚动到的位置
if (arg1 == OnScrollListener.SCROLL_STATE_IDLE) {
position = listView.getFirstVisiblePosition();
mEditor.putInt("list_pos", position);
mEditor.commit();
System.out.println("<position-->" + position);
//arg0.getScrollX();
}
}
@Override
public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
}
});
}
private List<String> getData() {
List<String> data = new ArrayList<String>();
for (int i = 0; i < 100; i++) {
data.add("==>" + i);
}
return data;
}
}