简体   繁体   中英

Android button becomes small in Nexus 5

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:

在此处输入图片说明

In Device: 在此处输入图片说明

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM