android - 按钮大小相对于 XML 布局中的父大小?

标签 android android-layout

是否可以在 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/

相关文章:

java - 保证 DateFormat 的年份字段只有两位数的便携方法

Android:相对布局内容在屏幕下方

android - 有没有办法让 Android 相机记录经历多个 Activity ?

java - Activity 作为大屏幕上的对话框

android - 无法在代码中使用 Textviews 和按钮

android - Google TV模拟器不支持本地播放和sdcard?

android - GoogleMap.getMyLocation() 返回 null

android - 提高 Android ListView 中的滚动平滑度

android - 缩放效果以滚动图像

android - 如何在 Android 上的 SharedPreferences 中保存/存储对象?