如何保持ListView的位置

时间:2010-04-27 20:49:11

标签: android

  

可能重复:
  Maintain/Save/Restore scroll position when returning to a ListView

当我去另一个活动(通过启动另一个意图)然后回来(按后退按钮)时,如何在我的活动中保持ListView的位置?

谢谢。

5 个答案:

答案 0 :(得分:27)

声明全局变量:

int index = 0;
ListView list;

并引用ListView中的onCreate()

list = (ListView) findViewById(R.id.my_list);

接下来,在onResume()中,在最后添加此行:

list.setSelectionFromTop(index, 0);

最后,在onPause中,将以下行添加到结尾:

index = list.getFirstVisiblePosition();

答案 1 :(得分:7)

做简单......

@Override
protected void onPause()
{
   index = listView.getFirstVisiblePosition();
   // store index using shared preferences   
}

和..

@Override
public void onResume() {
super.onResume();
// get index from shared preferences

if(listView != null){
    if(listView.getCount() > index)
        listView.setSelectionFromTop(index, 0);
    else
        listView.setSelectionFromTop(0, 0);
}

答案 2 :(得分:2)

您应该使用onSaveInstanceState存储滚动位置,然后使用onCreateonRestoreInstanceState进行恢复。

http://developer.android.com...#onSaveInstanceState ...

答案 3 :(得分:2)

请注意,使用ListView.getScrollY()无法正常恢复滚动位置。

请参阅Android: ListView.getScrollY() - does it work?

  

它指的是整个视图的滚动量,因此几乎总是为0。

在大多数情况下,这个值为0时发生在我身上。 具有ListView.setSelection()的ListView.getFirstVisiblePosition()可以更可靠地工作。

答案 4 :(得分:1)

@Override
protected void onPause()
{
    // Save scroll position
    SharedPreferences preferences = context.getSharedPreferences("SCROLL", 0);
    SharedPreferences.Editor editor = preferences.edit();
    int scroll = mListView.getScrollY();
    editor.put("ScrollValue", scroll);
    editor.commit();
}

@Override
protected void onResume()
{
    // Get the scroll position
    SharedPreferences preferences = context.getSharedPreferences("SCROLL", 0);
    int scroll = preferences.getInt("ScrollView", 0);
    mListView.scrollTo(0, scroll);
}