繁体   English   中英

Recyclerview 布局管理器在 Android 中滚动后获取 Position 中的视图

[英]Recyclerview Layout Manager Get View in Position After Scrolling in Android

Recyclerview使用它的LinearLayoutManager滚动,就像lm.scrollToPositionWithOffset(position, offset)一样。 如何在滚动前获得滚动 position 的视图? 滚动后将滚动返回 null 的视图,因为仍未创建。 我尝试过RunnableObserveronLayoutCompleted但仍然是 null。 如何获得视野?

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.  
}

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

  1. 修改您当前的 model: 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 }

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

View v = lm.getChildAt(position);
lm.scrollToPositionWithOffset(position, offset);
v.post(new Runnable() {
    @Override
    public void run() {
        // View is ready here.                
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM