how to set height of gridview programmatically android

前端 未结 2 1189
你的背包
你的背包 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()
        );
    }
    
    0 讨论(0)
  • 2021-02-05 12:01

    I think this should work:

    GridView gridView = (GridView)findViewById(...);
    ViewGroup.LayoutParams lp=new ViewGroup.LayoutParams(width,height);
    gridView.setLayoutParams(lp);
    
    0 讨论(0)
提交回复
热议问题