2012-03-26 31 views
5

我有一個使用XML解析每5秒刷新一次的列表視圖。刷新後,列表的當前位置返回到第一個位置。有沒有可能的方法來解決這個問題?更新arrayAdapter中的數據後列表視圖返回頂部postion

+0

請告訴我們如何刷新列表視圖。 – flo 2012-03-26 11:14:15

+0

可能您清除了列表數據並設置了全部新數據。您可以使用http://developer.android.com/reference/android/view/View.html scrollTo(INT,INT)方法 – pleerock 2012-03-26 11:24:08

+0

@flo '公共無效TimerMethod(){ \t \t runOnUiThread(新的Runnable() { \t \t \t公共無效的run(){ \t \t \t \t // Toast.makeText(getApplicationContext(), 「您好這是PIYUSH」, \t \t \t \t // Toast.LENGTH_LONG).show(); \t \t \t \t解析(鏈接); \t \t \t \t setAdapter(); \t \t \t} \t \t}); ' 每5秒調用一次該方法。 parse()用於xml解析,setAdapter()用於將新值設置爲listadapter – ASP 2012-03-26 13:06:41

回答

3

使用lv.smoothScrollToPosition(pos)其中pos可以是任何int,最好是適配器的長度,如果您希望listview到自動滾動到刷新的最後一個添加條目。

public void smoothScrollToPosition (int position) 


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

對於我的情況,這是唯一的選項,即使notifyDataSetChanged()被觸發,也是實際可行的。 – greg7gkb 2012-07-31 01:53:48

5

通過使用setAdapter()更新列表Android將重置位置。嘗試改變適配器。

我不知道你使用的是哪個適配器,所以這裏有兩個例子。

ArrayAdapter

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

的CursorAdapter

adapter.changeCursor(newCursor); 
+0

感謝您的回覆。這裏我使用了ArrayAdapter。但是我沒有得到你上面提到的「名單」。 – ASP 2012-03-26 14:46:33

+0

列表代表您正在使用的ListView。 – flo 2012-03-26 14:50:24

+0

你是一個好人,@flo – 2014-11-14 11:20:22

2

這個代碼將會幫助你....

// 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); 

乾杯:)

+0

優秀!!! ... – ajay 2015-06-30 17:24:49

-1

試試這個

adapter.notifyDataSetChanged(); 
相關問題