我在RecyclerView Adapter中使用SortedList,我想知道在我更改Adapter中的数据后,RecyclerView何时完成了更新(并调用了正确的方法,例如notifyItemRangeChanged)。有没有办法做到这一点?
我的问题是我需要在过滤其内容后将RecyclerView滚动到顶部。我从我的适配器上调用Activity方法来过滤其成员上的项目。之后,我只是在RecyclerView上调用scrollToPosition(0)并且它并不总是按预期工作,尤其是当列表上的更改操作仅为1项后。
以下是我在适配器上调用的更新方法代码:
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;
}
以下是我如何从Activity中调用它:
private RecyclerView gamesList;
private GameAdapter gamesAdapter;
@Override
public boolean onQueryTextChange(String newText) {
gamesAdapter.search(newText);
gamesList.scrollToPosition(0);
return false;
}
答案 0 :(得分:0)
您可以使用RecyclerAdapter.registerAdapterDataObserver(RecyclerView.AdapterDataObserver observer)
收听已更改的观点:
extends LayoutManager then override onItemUpdated(RecyclerView recyclerView, int positionStart, int itemCount, Object payload)
答案 1 :(得分: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.
}
});
答案 2 :(得分:0)
您可以为此使用add_action( 'plugins_loaded', 'pine_scripts' );
。
答案 3 :(得分:0)
您与this相关的问题接缝。
我尝试了这个,对我有用。这是Kotlin扩展名
fun RecyclerView.runWhenReady(action: () -> Unit) {
val globalLayoutListener = object: ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
action()
viewTreeObserver.removeOnGlobalLayoutListener(this)
}
}
viewTreeObserver.addOnGlobalLayoutListener(globalLayoutListener)
}
然后称呼它
myRecyclerView.runWhenReady {
// Your action
}