2013-08-19 42 views
1

我正在使用帶有自定義ArrayAdapter的ListView。 列表是一個無限的推文滾動。 從列表頂部插入對列表的更新。 我想獲得Twitter應用程序的效果。我不是在談論「滾動更新」,而是在更新後保持位置。更新Android ListView到頂部,然後到正確的位置

我剛剛實現了一些以這種方式工作的代碼。那就是:

 // get the position of the first visible tweet. 
     // pausedCounter traces the number of tweets in the waiting line 
     final int idx = listView.getFirstVisiblePosition() + pausedCounter; 
     View first = listView.getChildAt(0); 
     int position = 0; 


     if (first != null) 
      position = first.getTop(); 

     // here I update the listView with the new elements 
     for (Tweet[] tweets1 : pausedTweets) 
      super.updateTweets(tweets1); 


     final int finalPosition = position; 

     // this code maintain the position 
     listView.post(new Runnable() { 
      @Override 
      public void run() { 
       listView.setSelectionFromTop(idx, finalPosition); 
      } 
     }); 

這段代碼的問題是,對於瞬間的ListView進入到列表的第一個元素,然後在setSelectionFromTop踢和它關係到正確的位置。

這種「閃爍」令人討厭,我想刪除它。

回答

1

我發現僅此解決方案:

 // add the new elements to the current ArrayAdapter 
     for (Tweet[] tweets1 : pausedTweets) 
      super.updateTweets(tweets1); 

     // create a NEW ArrayAdapter using the data of the current used ArrayAdapter 
     // (this is a custom constructor, creates an ArrayAdapter using the data from the passed) 
     TweetArrayAdapter newTweetArrayAdapter = 
       new TweetArrayAdapter(context, R.layout.tweet_linearlayout, (TweetArrayAdapter)listView.getAdapter()); 

     // change the ArrayAdapter of the listView with the NEW ArrayAdapter 
     listView.setAdapter(newTweetArrayAdapter); 

     // set the position. Remember to add as offset the number of new elements inserted 
     listView.setSelectionFromTop(idx, position); 

這樣,我沒有「忽隱忽現」了!