在列表视图中每次刷新时保持滚动位置

时间:2013-04-18 20:39:10

标签: android listview scroll

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

4 个答案:

答案 0 :(得分: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
    }
});

答案 1 :(得分:6)

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

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

添加这些属性,您的ListView将始终在底部绘制,就像您希望它在聊天中一样。

或者如果您想将其保留在以前的位置,请将alwaysScroll替换为normal

in the android:transcriptMode attribute. 

干杯!!!

答案 2 :(得分: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的顶部定位。< / p>

答案 3 :(得分:1)

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

相关问题