RecyclerView LayoutManager findViewByPosition返回null
我对获得RecyclerView第一项大小的权利和第一可能时刻感兴趣?
我试过使用:
recyclerView.setLayoutManager(new GridLayoutManager(context, 2));
recyclerView.setAdapter(new MyDymmyGridRecyclerAdapter(context));
recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
     @Override
     public void onGlobalLayout() {
         recyclerView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
         View firstRecyclerViewItem = recyclerView.getLayoutManager().findViewByPosition(0);
         // firstRecyclerViewItem is null here
     }
});
但此时它将返回null。
  如果您使用OnGlobalLayoutListener ,则应该记住onGlobalLayout可以多次调用。  其中一些调用甚至可以在Layout准备就绪之前发生(并且准备就绪是指通过调用view.getHeight()或view.getWidth() )获得View的维数的时刻。  所以实施你的方法的正确方法是: 
recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
     @Override
     public void onGlobalLayout() {
         int width = recyclerView.getWidth();
         int height = recyclerView.getHeight();
         if (width > 0 && height > 0) {
             if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                 recyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
             } else {
                 recyclerView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
             }
         }
         View firstRecyclerViewItem = recyclerView.getLayoutManager().findViewByPosition(0);
     }
});
  除此之外,您仍然需要确保在调用findViewByPosition(0)时: 
RecyclerView's Adapter至少有一个数据元素。 RecyclerView可以看到位置0 View 告诉我,如果这能解决你的问题,如果不是还有另一种做你需要的方法。
在我的扩展RecyclerView像这样覆盖onChildAttachedToWindow 
@Override
public void onChildAttachedToWindow(View child) {
    super.onChildAttachedToWindow(child);
    if (!mIsChildHeightSet) {
        // only need height of one child as they are all the same height
        child.measure(0, 0);
        // do stuff with child.getMeasuredHeight()
        mIsChildHeightSet = true;
    }
}
我有这种类型的问题。 我想在recylerview的第一个可见位置默认执行点击。 我在onResume上编写了代码,但没有奏效。 我通过在onWindowFocusChanged方法中写入代码解决了我的问题
    @Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if(isCalledForTheFirstTime)
    {
        LinearLayoutManager manager= (LinearLayoutManager) rcViewHeader.getLayoutManager();
        int pos= manager.findFirstCompletelyVisibleItemPosition();
        View view=manager.findViewByPosition(pos);
        if(view!=null)
        {
            view.performClick();
        }
        // change the vaule so that it would not be call in case a pop up appear or disappear 
        isCalledForTheFirstTime=false;
    }
}
上一篇: RecyclerView LayoutManager findViewByPosition returns null
