Set width of Button in Android

后端 未结 5 1188
没有蜡笔的小新
没有蜡笔的小新 2021-02-12 22:04

How can I set a fixed width for an Android button? Everytime I try to set a fixed width it fills the current parent (the RelativeView). Here is my XML:



        
5条回答
  •  萌比男神i
    2021-02-12 23:01

    The best and easiest way to set a button dynamically is

     Button index=new Button(this);
     int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 45, getResources().getDisplayMetrics());             
     int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 42, getResources().getDisplayMetrics());
    

    The height and width in pixels px. 45 being the height in dp and 42 being the width in dp.

     index.setLayoutParams(new .LayoutParams(width, height));
    

    So, for example, if you've placed your button within a TableRow within a TableLayout, you should have it as TableRow.LayoutParams

     index.setLayoutParams(new TableRow.LayoutParams(width, height));
    

提交回复
热议问题