2017-04-12 215 views
0

我在RecyclerView適配器中使用SortedList,我想知道RecyclerView在更改Adapter中的數據(並調用適當的方法,例如notifyItemRangeChanged)後何時完成更新。有沒有辦法做到這一點?如何找出RecyclerView已完成更新?

我的問題是,我需要在過濾其內容後將RecyclerView滾動到頂部。我從我的適配器上的Activity方法調用了其成員上的項目。之後,我只是在RecyclerView上調用scrollToPosition(0),它並不總是像預期的那樣工作,特別是當列表上的更改操作只有一個項目時。

以下是更新方法的代碼,我在我的適配器上呼籲:

private SortedList<Game> games; 
private ArrayList<Game> allGames; 

public void search(String query) { 
    replaceAll(filterGames(query)); 
} 

public void replaceAll(Collection<Game> games) { 
    this.games.beginBatchedUpdates(); 
    List<Game> gamesToRemove = new ArrayList<>(); 
    for (int i = 0; i < this.games.size(); i++) { 
     Game game = this.games.get(i); 
     if (!games.contains(game)) { 
      gamesToRemove.add(game); 
     } 
    } 
    for (Game game : gamesToRemove) { 
     this.games.remove(game); 
    } 
    this.games.addAll(games); 
    this.games.endBatchedUpdates(); 
} 

private Collection<Game> filterGames(String query) { 
    query = query.toLowerCase(); 
    List<Game> filteredGames = new ArrayList<>(); 
    for (Game game : allGames) { 
     String gameTitle = game.getTitle().toLowerCase(); 
     if (gameTitle.contains(query)) { 
      filteredGames.add(game); 
     } 
    } 
    return filteredGames; 
} 

在這裏,我怎麼稱呼它的活動:

private RecyclerView gamesList; 
private GameAdapter gamesAdapter; 

@Override 
public boolean onQueryTextChange(String newText) { 
    gamesAdapter.search(newText); 
    gamesList.scrollToPosition(0); 
    return false; 
} 
+0

但是,您需要什麼?什麼是用例? – azizbekian

+0

我想在添加/刪除項目後將RecyclerView滾動到頂部。當我在適配器上開始更新時嘗試滾動時,出現問題,因爲項目仍在處理中。 – ostojan

+0

'因爲項目仍在處理中'如果它們不在屏幕上,它們如何「被處理」,因此它們從窗口中分離出來? – azizbekian

回答

0

可以使用RecyclerAdapter.registerAdapterDataObserver(RecyclerView.AdapterDataObserver observer)

收聽改變了意見:

extends LayoutManager then override onItemUpdated(RecyclerView recyclerView, int positionStart, int itemCount, Object payload) 
+0

我已經厭倦了這一點,但在這種方式,我只能找出更新被要求,沒有完成。 – ostojan

+0

它看起來像你需要使用LayoutManager.onItemUpdated –

+0

這幾乎是我想要的。如果我從列表中刪除項目,它會正常工作。當我在實際第一項之前添加項目並在onItemUpdated中調用scrollToPosition(0)時,它不起作用。 – ostojan

0

嘗試使用,

recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
       @Override 
       public void onGlobalLayout() { 
        //At this point the layout is complete and the 
        //dimensions of recyclerView and any child views are known. 
       } 
      }); 
+0

這還不是我要找的。此方法看起來像被稱爲每個應用程序框架。即使我設置了標誌,我編輯了數據,然後執行我的操作RecyclerView中的更改仍在繼續。 – ostojan