我有一个附加了 PageSnapHelper 的 GridLayout RecyclerView,它基本上就像一个垂直线性 RecyclerView (我继承了代码,不知道为什么这样做)。目标是突出显示当前在视图中居中的项目。滚动是从由两个菜单项驱动的代码完成的,以模拟从遥控器前进和后退。滚动视图工作正常。问题似乎是,当我收听滚动事件结束时,会出现动画,这会弄乱我的代码以在项目周围绘制突出显示。这是我用来根据菜单项滚动视图的代码:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//Get which arrow was pressed
int id = item.getItemId();
//Get count of items
int itemCount = recyclerView.getAdapter().getItemCount();
//Condition to moving down the list
if (id == R.id.next) {
//Make sure we're within bounds of the of the view from the top
if(count>=itemCount-1) {
return super.onOptionsItemSelected(item);
}
//Increment to count to next ViewHolder
count++;
//Condition for moving up list
} else if (id == R.id.prev) {
//Make sure we're within bounds
if(count == 0){
return super.onOptionsItemSelected(item);
}
//Decremennt to previous ViewHolder
count--;
}
//Scroll the RecyclerView to the position we want
layoutManager.setIsNext(id == R.id.next);
recyclerView.smoothScrollToPosition(count);
//If the item is already in view, then no scroll event is necessary and we can access the ViewHolder
HighlightViewHolder(count);
//In the event that the ViewHolder is off-screen listen for the end of the scrolling event to ensure the ViewHolder
//is created and in correct position on the screen
RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() {
//Add a listener to that looks out for when the scrolling is complete
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
Log.i("ScrollListener", "Scrolling has ended");
HighlightViewHolder(count);
recyclerView.removeOnScrollListener(this);
}
};
recyclerView.addOnScrollListener(scrollListener);
return super.onOptionsItemSelected(item);
当应用程序第一次启动并且我按下前进按钮时,第一项突出显示就好了:
我期望发生的是,当滚动事件结束时,该项目处于其中心位置。根据我所看到的,我认为还有一些动画事件仍在发生,我应该寻找完成。我的突出显示代码依赖于有问题的视图位于其预期位置。我是 android 新手,我对 RecyclerView 动画的搜索将我带到了 ItemAnimator。但是阅读文档我不确定这是否是我正在寻找的。有任何想法吗?