是否可以在 XML 布局文件中设置按钮的大小,这样一方面,它不会占用父级(屏幕)的整个宽度,另一方面另一方面,不使用绝对像素值?
为了更好地解释我的问题,以下代码段中的问题是 "match_parent"
占据了整个宽度:
<Button android:id="@+id/btn_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="16px"
android:paddingLeft="16px"
android:paddingRight="16px"
android:paddingTop="16px"
android:text="@string/first_button" />
我知道可以控制大小 during runtime但我很想知道这在 XML 文件中是否也可行。
是否有像 android:layout_width="match_HALF_parent"
这样的东西?
最佳答案
布局权重可以做到这一点。基本上你需要做的是在父布局中设置一个 weightSum,然后在子布局中设置一个 layout_weight:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:weightSum="2" android:orientation="horizontal">
<Button android:id="@+id/btn_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingBottom="16px"
android:paddingLeft="16px"
android:paddingRight="16px"
android:paddingTop="16px"
android:text="@string/first_button" />
</LinearLayout>
决定 child 宽度的是 parent 的weightSum和 child 的体重之间的关系:在本例中为一半;如果我们将父项的权重总和增加到 3,则子项的宽度将是其父项的三分之一。
我在我的 blog 上写过这个.
关于android - 按钮大小相对于 XML 布局中的父大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5899549/