how to set height of gridview programmatically android

前端 未结 2 1220
你的背包
你的背包 2021-02-05 11:40

I want to set the height of my Gridview programmatically in my application.

Is there any way to implement that?

I just want to change the gr

2条回答
  •  悲哀的现实
    2021-02-05 11:56

    Use this, as you want to retain the current layoutParams:

    ViewGroup.LayoutParams layoutParams = yourGridview.getLayoutParams();
    layoutParams.height = 50; //this is in pixels
    yourGridview.setLayoutParams(layoutParams);
    

    Edit: If you want to input the height as dp instead of pixels, translate the dp amount to pixels:

    public static int convertDpToPixels(float dp, Context context){
        Resources resources = context.getResources();
        return (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                dp, 
                resources.getDisplayMetrics()
        );
    }
    

提交回复
热议问题