如何设置RecyclerView最大高度

问题描述:

我想设置RecylerView的最大高度.我可以使用以下代码设置最大高度.下面的代码使当前屏幕的高度为60%.

I want to set Max Height of RecylerView.I am able to set max height using below code.Below code makes height 60% of current screen.

     DisplayMetrics displaymetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int a = (displaymetrics.heightPixels * 60) / 100;
    recyclerview1.getLayoutParams().height = a;

但是现在的问题是,如果没有物品,那么它的高度也是60%. 因此,当其中没有任何项目时,我想将其高度设置为0.

But now problem is that, if it have no item then also its height is 60%. So I want to set its height 0 when no item in it.

我想要实现某些目标.

    if(recyclerview's height > maxHeight)
then set recyclerview's height to maxHeight
    else dont change the height of recyclerview.

我该如何设置? 请帮助我,我坚持下去

How can i set it? Please help me, I am stuck with it

这里是您需要的东西.子类化RecyclerView并重写onMeasure,如下所示:

Here is something, you need. Subclass the RecyclerView and override onMeasure as following:

@Override
protected void onMeasure(int widthSpec, int heightSpec) {
    heightSpec = MeasureSpec.makeMeasureSpec(Utils.dpsToPixels(240), MeasureSpec.AT_MOST);
    super.onMeasure(widthSpec, heightSpec);
}

请确保您提供适当的像素数作为makeMeasureSpec()中的第一个参数.我个人需要RecyclerView,最多为240dps.

Make sure, you give proper number of pixels as the first argument in makeMeasureSpec(). I personally needed RecyclerView, that is 240dps at most.