在安卓系统中设置按钮的宽度

2022-09-02 20:20:34

如何为安卓按钮设置固定宽度?每次我尝试设置固定宽度时,它都会填充当前父项(相对视图)。这是我的XML:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout android:id="@+id/relativelayout" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">

    <EditText android:layout_height="wrap_content" android:editable="false" android:layout_width="fill_parent" android:id="@+id/output"></EditText>

    <Button android:layout_height="wrap_content" android:id="@+id/Button01" android:layout_below="@id/output" android:text="7" android:layout_width="wrap_content"></Button>
    <Button android:layout_below="@id/output" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/Button02" android:layout_toRightOf="@+id/Button01" android:text="8"></Button>
    <Button android:layout_below="@id/output" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/Button03" android:layout_toRightOf="@+id/Button02" android:text="9"></Button>
</RelativeLayout>

如何给它一个固定的宽度?
更新
假设我有几个按钮,我想要彼此相同的大小和整个视图的1/3(纵向),然后我想要一个宽度加倍的按钮。然后是一个高度加倍的按钮。我怎么能完成这个手动调整它们的大小?


答案 1

要完成所需的操作,可以使用具有加权和的线性布局。例如,您可以将 WeightSum 设置为 9。如果你把三个按钮的重量放在里面到1个每个。它们将占用该位置的1/3,您可以将2用于另一个对象。这个物体的两倍大。

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

编辑:我想添加一点,要使其正常工作,您必须将宽度或高度设置为0px(取决于它是水平布局还是垂直布局)。


答案 2

而不是你可以使用固定的像素大小,例如或更好的方法:android:layout_width="wrap_content"android:layout_width="20px"android:layout_width="20dp"

您还可以在代码中以编程方式设置宽度:Button.setWidth(int width)

关于您的更新:

我不知道这是否是一个好的解决方案,但我工作。您可以使用

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

以读取屏幕分辨率,然后根据度量设置按钮大小。宽度像素和度量。高度像素


推荐