[英]keep Scroll position with every refresh in list view
我在我的應用程序中設置了一個計時器,我可以從Web服務獲取一些信息,並生成一個列表視圖來顯示。 現在我的問題是,每次計時器運行時,滾動回到開頭......
如何在列表視圖中每次刷新時保持滾動位置?
我的部分代碼:
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(DashboardActivity.this,
all_chat,
R.layout.list_item,
new String[] { TAG_FULLNAME,
TAG_DATE,
TAG_MESSAGE },
new int[] { R.id.fullname,
R.id.date,
R.id.message }
);
// updating listview
setListAdapter(adapter);
}
});
TNX。
不要調用setAdapter()
。 做這樣的事情:
ListAdapter adapter; // declare as class level variable
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
*/
if (adapter == null) {
adapter = new SimpleAdapter(
DashboardActivity.this, all_chat, R.layout.list_item, new String[]{TAG_FULLNAME, TAG_DATE, TAG_MESSAGE},
new int[]{R.id.fullname, R.id.date, R.id.message});
setListAdapter(adapter);
} else {
//update only dataset
allChat = latestetParedJson;
((SimpleAdapter) adapter).notifyDataSetChanged();
}
// updating listview
}
});
您可以將以下屬性添加到xml中的ListView
。
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll"
添加這些屬性,您的ListView
將始終在底部繪制,就像您希望它在聊天中一樣。
或者如果你想將它保持在以前的位置,請將alwaysScroll
替換為normal
in the android:transcriptMode attribute.
干杯!!!
我有同樣的問題,嘗試了很多東西來阻止列表更改其滾動位置,包括:
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll"
而不是調用listView.setAdapter();
在我找到這個答案之前,它都沒有奏效:
看起來像這樣:
// save index and top position
int index = mList.getFirstVisiblePosition();
View v = mList.getChildAt(0);
int top = (v == null) ? 0 : (v.getTop() - mList.getPaddingTop());
// ...
// restore index and position
mList.setSelectionFromTop(index, top);
說明:
ListView.getFirstVisiblePosition()
返回頂部可見列表項。 但是此項可能會部分滾動到視圖之外,如果要恢復列表的確切滾動位置,則需要獲取此偏移量。 因此ListView.getChildAt(0)
返回頂部列表項的View
,然后View.getTop() - mList.getPaddingTop()
返回其從ListView
頂部的相對偏移量。 然后,為了恢復ListView
的滾動位置,我們使用我們想要的項目的索引調用ListView.setSelectionFromTop()
,並使用偏移量將其頂邊定位在ListView
的頂部。
Chris Banes寫了一篇很好的文章 。 對於第一部分,只需使用ListView#setSelectionFromTop(int)
將ListView
保持在相同的可見位置。 為了防止ListView
閃爍,解決方案是簡單地阻止ListView布置它的子節點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.