2013-04-18 43 views
9

我在我的应用程序中设置了一个计时器,我可以从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。

+0

http://stackoverflow.com/a/3035521/931982 – stinepike

+0

可能重复[维护/保存/恢复滚动位置时返回到ListView](http://stackoverflow.com/questions/3014089/maintain-save -restore-scroll-position-when-returning-to-listview) – stinepike

+0

这些链接并不能解决我的问题,因为我的问题是另一回事。我的列表视图自动从Web服务接收数据,然后将位置移回到开始位置(顶部位置)....,我希望你解决我的问题...... tnx。 –

回答

6

您可以将以下属性添加到您的xml中的ListView

android:stackFromBottom="true" 
android:transcriptMode="alwaysScroll" 

添加这些属性,你的ListView将永远在底部像你希望它是在聊天绘制。

,或者如果你想保持它在同一个地方它之前,更换alwaysScrollnormal

in the android:transcriptMode attribute. 

干杯!

1

有一个good article by Chris Banes。对于第一部分,只需使用ListView#setSelectionFromTop(int)即可将ListView保持在相同的可见位置。为了防止ListView闪烁,解决方案是简单地阻止ListView布置它的子项。

+1

阻止什么? – mixel

+0

哎呦,更新了 – f2prateek

14

请勿拨打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 
    } 
}); 
+3

“allChat”和“all_chat”是同一个变量吗?将allChat传递给适配器构造函数,然后更改allChat引用并不意味着将在适配器中更改allChat。 – mixel

2

我有同样的问题,尝试了很多的东西,以防止改变其滚动位置,列表包含:

android:stackFromBottom="true" 
android:transcriptMode="alwaysScroll" 

,而不是调用listView.setAdapter(); 无它工作,直到我发现this answer

,看起来像这样:

// 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的顶部开始定位其顶边的偏移量一起调用。