【问题标题】:List view back to top postion after updating data in arrayadapter更新 arrayadapter 中的数据后,列表视图返回顶部位置
【发布时间】:2012-03-26 11:06:37
【问题描述】:

我有一个使用 XML 解析每 5 秒刷新一次的列表视图。刷新后,列表的当前位置回到第一个位置。有没有可能解决这个问题的方法?

【问题讨论】:

  • 请告诉我们您是如何刷新列表视图的。
  • 可能您清除了列表数据并设置了所有新数据。可以使用developer.android.com/reference/android/view/View.htmlscrollTo(int, int) 方法
  • @flo public void TimerMethod() { runOnUiThread(new Runnable() { public void run() { // Toast.makeText(getApplicationContext(), "Hi this is piyush", // Toast.LENGTH_LONG).show(); parse(link); setAdapter(); } }); 每 5 秒调用一次此方法。 parse() 用于 xml 解析和 setAdapter() 用于为 listadapter 设置新值

标签: android listview android-arrayadapter


【解决方案1】:

通过使用 setAdapter() 更新列表,Android 会重置位置。请尝试更改适配器。

我不知道您使用的是哪个适配器,所以这里举两个例子。

阵列适配器

adapter = list.getAdapter();
if (adapter == null) {
    // Create new adapter + list.setAdapter()
} else {
    adapter.clear();
    adapter.addAll(newData);
    adapter.notify(notifyDataSetChanged());
}

光标适配器

adapter.changeCursor(newCursor);

【讨论】:

  • 感谢您的回复。这里我使用 ArrayAdapter。但我没有得到你上面提到的“列表”。
  • list 代表您正在使用的 ListView。
【解决方案2】:

使用lv.smoothScrollToPosition(pos),其中 pos 可以是任何 int,最好是适配器的长度,如果您希望列表视图在刷新时自动滚动到最后添加的条目。

public void smoothScrollToPosition (int position) 


Smoothly scroll to the specified adapter position. The view will scroll such that the indicated position is displayed.

【讨论】:

  • 就我而言,这是唯一一个即使在 notifyDataSetChanged() 触发后也能真正起作用的选项。
【解决方案3】:

此代码将帮助您....

// get position of listview
int index = listView.getFirstVisiblePosition();
View v = listView.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();

// notify dataset changed or re-assign adapter here

//re-assign the position of listview after setting the adapter again
listView.setSelectionFromTop(index, top);

干杯:)

【讨论】:

    【解决方案4】:

    试试这个

    adapter.notifyDataSetChanged();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 2017-08-17
      • 1970-01-01
      • 2012-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多