How do I make WRAP_CONTENT work on a RecyclerView

后端 未结 19 1686
自闭症患者
自闭症患者 2020-11-22 12:49

I have a DialogFragment that contains a RecyclerView (a list of cards).

Within this RecyclerView are one or more CardVi

19条回答
  •  盖世英雄少女心
    2020-11-22 13:40

    Try this (It's a nasty solution but It may work): In the onCreate method of your Activity or in the onViewCreated method of your fragment. Set a callback ready to be triggered when the RecyclerView first render, like this:

    vRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    calculeRecyclerViewFullHeight();
                }
            });
    

    In the calculeRecyclerViewFullHeight calculate the RecyclerView full height based in the height of its children.

    protected void calculateSwipeRefreshFullHeight() {
            int height = 0;
            for (int idx = 0; idx < getRecyclerView().getChildCount(); idx++ ) {
                View v = getRecyclerView().getChildAt(idx);
                height += v.getHeight();
            }
            SwipeRefreshLayout.LayoutParams params = getSwipeRefresh().getLayoutParams();
            params.height = height;
            getSwipeRefresh().setLayoutParams(params);
        }
    

    In my case my RecyclerView is contain in a SwipeRefreshLayout for that reason I'm setting the height to the SwipeRefreshView and not to the RecyclerView but if you don't have any SwipeRefreshView then you can set the height to the RecyclerView instead.

    Let me know if this helped you or not.

提交回复
热议问题