简体   繁体   English

Nexus 5中的Android按钮变小

[英]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). 它在Emulator中清晰可见,而在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. 为了使Device中的按钮清晰可见,我还需要做什么。 TIA 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. Nexus 5具有很高的像素密度,因此您的按钮非常小。



There a now 2 ways to get around this: 现在有两种解决方法:

1. define the values in your dimen.xml in the resources 1.在资源中的dimen.xml中定义值

In your resources there is a folder "values" that should contain a dimen.xml. 您的资源中有一个文件夹“值”,其中应包含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 2.使用XML

But if you can define the whole layout of your activity in an XML-file. 但是,如果您可以在XML文件中定义活动的整体布局。

In there you can define the width and the height in "dp" like this: 在这里,您可以像这样在“ dp”中定义宽度和高度:

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. 必须使用“ dp”而不是“ px”来使每个设备上的按钮看起来完全相同。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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