Set width of Button in Android

喜你入骨 提交于 2019-12-03 10:17:05

To accomplish what you want, you can use a LinearLayout with a weightsum. For example, you can put a WeightSum of 9. If you put the weight of three button inside to 1 each. They will take 1/3 of the place, and you can put 2 for another object. This object will be twice as big as the other.

http://developer.android.com/reference/android/widget/LinearLayout.html#setWeightSum(float)

Edit: I would like to add that for this to work correctly, you have to set the width or height to 0px (depending on if it's an horizontal or a vertical layout).

RoflcoptrException

Instead of android:layout_width="wrap_content" you can use a fixed pixelsize like for example android:layout_width="20px" or a better way: android:layout_width="20dp"

you can also set the width programatically in the code: Button.setWidth(int width)

Concerning your update:

I don't know if it is a good solution, but i works. You could use

 DisplayMetrics metrics = new DisplayMetrics();
 getWindowManager().getDefaultDisplay().getMetrics(metrics);

to read the screen resolution and then set the button sizes according to metrics.widthPixel and metrics.heightPixel

Use minWidth and minHeight to set the width and height of a button.

<Button android:layout_height="wrap_content"
 android:id="@+id/Button01" 
 android:layout_below="@id/output" 
 android:text="7" 
 android:minWidth="100dp">
</Button>

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 <Parent>.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));
Rathiga Jesika

add android:minwidth line in that code.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!