首页 > 解决方案 > Recyclerview布局管理器在Android中滚动后获取视图位置

问题描述

RecyclerviewLinearLayoutManager这样滚动的lm.scrollToPositionWithOffset(position, offset)。如何在滚动之前获取滚动位置的视图?将滚动的视图在滚动后返回 null,因为仍未创建。我试过了RunnableObserveronLayoutCompleted仍然为空。如何获得视野?

lm.scrollToPositionWithOffset(position, offset);

recyclerView.post(new Runnable(){
    @Override
    public void run(){
        View v1 = recyclerView.getChildAt(position); // returning null.
        View v2 = recyclerView.getLayoutManager().getChildAt(position); // returning null.
    }
});

recyclerView.getViewTreeObserver()
   .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
       @Override
       public void onGlobalLayout() {
           View v1 = recyclerView.getChildAt(position); // returning null.
           View v2 = recyclerView.getLayoutManager().getChildAt(position); // returning null.
       recyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}});

@Override // in LinearLayoutManager
public void onLayoutCompleted(RecyclerView.State state) {
    super.onLayoutCompleted(state);
    View v1 = recyclerView.getChildAt(position); // returning null.
    View v2 = this.getChildAt(position); // returning null.  
}

标签: javaandroidandroid-layoutandroid-recyclerview

解决方案


如果您尝试修改视图内容,您应该这样做:

  1. 修改您当前的模型:itemList.get(position) // and change any property here to handle that state

  2. 称呼adapter.notifyItemChanged(position)

  3. 确保您有正确的逻辑ViewHolder来处理此更改,并且应该修改您的View

但如果你真的想通过 改变事情,ViewHolder你也可以这样做:recyclerView.findViewHolderForAdapterPosition(position)然后:

if (null != holder) { holder.itemView.findViewById(R.id.YOUR_ID) // call any method do you want to }

我真的推荐第一个选项,但这取决于你。希望这对你有帮助!


推荐阅读