簡體   English   中英

自動滾動ListView?

[英]Autoscroll a ListView?

我已經實現了一個ListView來讀取rss提要,並且我想為此列表視圖實現自動滾動。

我可能會使用類似:

listView.post(new Runnable() {
            @Override
            public void run() {
                listView.smoothScrollToPosition(???);
            }
        });

但是如何順利讀取所有位置,然后從頭開始?

好吧,您可以使用某種計數器簡單地遍歷列表視圖中的元素:

int count = listView.getCount();
for (int i = 0; i < count; i++) {
    listView.post(new Runnable() {
        @Override
        public void run() {
            listView.smoothScrollToPosition(i);
        }
    }); 
}
// Once the method gets to here, i == count and we're at the last position
// So you can use some logic to scroll back to the top e.g. 
// listView.smoothScrollToPosition(0)

除了使用post() ,您可能還想考慮使用Timer對象,因為我認為對何時執行發布隊列上的可運行對象沒有太多控制權。

編輯

因此,我設法通過使用帶有固定速率的計划ScrollTimerTaskTimer來獲得基本但有效的示例

//This is an inner class, with i an int in the Activity, starting at 0;
public class ScrollTimerTask extends TimerTask {

    @Override
    public void run() {
        if (i < getListView().getCount()) {
            getListView().smoothScrollToPosition(i);
            i++;
        }
        else {
            getListView().smoothScrollToPosition(0);
            i == 0;
        }
}

然后,要開始向下移動列表,請調用new Timer().scheduleAtFixedRate(new ScrollTimerTask(), 0, 1000); 這將在沒有延遲的情況下開始滾動,並且將每1000ms安排滾動任務。

請注意,這是基本步驟,當您關閉活動時,它將崩潰,並會連續運行。 為防止崩潰,我建議保留對Timer對象的引用,並在Activity的onPause()方法中調用Timer.cancel() 但這是一個起點!

添加一個大頁腳/頁眉,並在到達末尾(0)時跳轉並重新開始滾動。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM