How to set RecyclerView Max Height

前端 未结 12 1655
陌清茗
陌清茗 2020-12-01 15:55

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 displ         


        
12条回答
  •  囚心锁ツ
    2020-12-01 16:27

    If you have a RecyclerView designed to hold items of equal physical size and you want a no-brainer way to limit its height without extending RecyclerView, try this:

    int maxRecyclerViewHeightPixels = (int) TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP,
        MAX_RECYCLERVIEW_HEIGHT_DP,
        getResources().getDisplayMetrics()
    );
    
    MyRecyclerViewAdapter myRecyclerViewAdapter = new MyRecyclerViewAdapter(getContext(), myElementList);
    myRecyclerView.setAdapter(myRecyclerViewAdapter);
    
    ViewGroup.LayoutParams params = myRecyclerView.getLayoutParams();
    
    if (myElementList.size() <= MAX_NUMBER_OF_ELEMENTS_TO_DISPLAY_AT_ONE_TIME) {
        myRecyclerView.setLayoutParams(new LinearLayout.LayoutParams(
             LinearLayout.LayoutParams.MATCH_PARENT,
             LinearLayout.LayoutParams.WRAP_CONTENT));
        //LinearLayout must be replaced by whatever layout type encloses your RecyclerView
    }
    else {
        params.height = maxRecyclerViewHeightPixels;
        myRecyclerView.setLayoutParams(params);
    }
    

    This works both for Linear and Grid RecyclerViews, you just need to play with the numbers a bit to suit your taste. Don't forget to set the height to WRAP_CONTENT after you populate the RecyclerView.

    You may also have to set the height again every time the size of myElementList changes, but that's not a big issue.

提交回复
热议问题