我有一个按钮,大小为width=216
和height=110
在设备屏幕分辨率为1080 x 1920.当我更改为其他设备(较小的分辨率)时,按钮是如此之大。因此,我需要编写一个功能来根据屏幕的设备分辨率动态更改按钮大小。首先,我会检查目标设备的分辨率,然后根据我目前的设备进行更改。但是,按钮分辨率不正确。我该如何解决它?这是我的代码如何根据屏幕设备更改按钮大小?
我在1080×1920
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center"
>
<Button
android:id="@+id/btn"
android:layout_width="216dp"
android:layout_height="110dp"
android:layout_gravity="center"
android:scaleType="fitCenter"
/>
</LinearLayout>
代码更改为动态的方式:
public int WIDTH ;
public int HEIGHT ;
//Get screen resolution
DisplayMetrics metrics = getResources().getDisplayMetrics();
HEIGHT = metrics.heightPixels;
WIDTH= metrics.widthPixels;
int height_px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 110, getResources().getDisplayMetrics());
int weight_px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 216, getResources().getDisplayMetrics());
int width_linearlayout = Math.round((float)weight_px/1080*WIDTH);
int height_linearlayout = Math.round((float)height_px/1920*HEIGHT);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width_linearlayout,height_linearlayout);
btn.setLayoutParams(layoutParams);
你有没有通过[支持多种布局(HTTPS阅读://开发商。 android.com/guide/practices/screens_support.html)?如果不是的话,我建议你继续看看。 – Abbas
@Abbas:它来自xml和drawable文件夹。我想用编程来改变我的按钮 – user8264
然后,你将不得不做很多值得的工作。我建议你通过布局来做到这一点。检查@slackwars答案,这是实现你想要的最好的方式。但是,解决方案仅适用于具有相似布局的情况。对于不同大小的不同布局,您必须添加多个布局。 – Abbas