Android button becomes small in Nexus 5

189 views Asked by At

I am creating a button dynamically for a particular screen. It is clearly visible in Emulator where as looking very small in Device (Nexus 5).

In Emulator:

enter image description here

In Device: enter image description here

I am using below code for button creation in code:

LayoutParams updt_btn_params = new LayoutParams();
update_data = new Button(this);
update_data.setText("Update");
update_data.setTextSize(9);
updt_btn_params.width=80;
updt_btn_params.height=45;
updt_btn_params.gravity=Gravity.CENTER_HORIZONTAL;
update_data.setOnClickListener(update_listnr);
update_data.setLayoutParams(updt_btn_params);

What else I have to do for getting buttons clearly in Device. TIA

2

There are 2 answers

0
Thorben On BEST ANSWER

The problem is that you are using these:

updt_btn_params.width=80;
updt_btn_params.height=45;

With this you are setting the width and the height in pixels, which is something you should never do. Different devices have different pixel densities which means that the size of the pixels varies from device to device. The Nexus 5 has quite a high pixel density which makes your buttons very small.



There a now 2 ways to get around this:

1. define the values in your dimen.xml in the resources

In your resources there is a folder "values" that should contain a dimen.xml. In this you can define your dimensions for the Buttons like this:

<dimen name="width">80dp</dimen>
<dimen name="height">45dp</dimen>

Then you can read them into your code via:

updt_btn_params.width = getResources().getDimensionPixelSize(R.dimen.width);
updt_btn_params.height = getResources().getDimensionPixelSize(R.dimen.height);

2. use XML

But if you can define the whole layout of your activity in an XML-file.

In there you can define the width and the height in "dp" like this:

layout_width="80dp"
layout_height="45dp"

It is essential to use "dp" instead of "px" to make the Buttons look exactly the same on every device.

0
Shiva On
float ht_px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, ht, getResources().getDisplayMetrics());
float wt_px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, wt, getResources()