如何使用XML根据图像大小调整Android组件的尺寸

4
我使用XML布局创建器在Android中创建了一个自定义图标栏,其中包含一个RadioGroup和一个LinearLayout(下面附有XML)。RadioGroup中的每个RadioButton都有一个自定义的drawable作为其android:button属性(具有选中和未选中状态)。
LinearLayout本身位于RelativeLayout中,以便可以出现在屏幕上的任意位置(例如侧边栏)。
这些可绘制对象的宽度为55像素,所有这些视图的android:layout_width属性均为wrap_content。
当我将此组件设置为可见并与屏幕底部左对齐时,只有大约四分之三的RadioButton图像宽度可见。将RelativeLayout的layout_width属性设置为fill_parent可以纠正此问题并导致整个按钮显示。
但是,这意味着按钮组跨越整个屏幕消耗点击事件。
如何使整个按钮出现,并且仅有按钮区域响应点击?硬编码可绘制对象的宽度不是特别理想的解决方案。
<RelativeLayout android:id="@+id/RelativeLayout01" android:layout_width="wrap_content" android:layout_height="wrap_content">
    <LinearLayout android:id="@+id/LinearLayout02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_below="@+id/LinearLayout01" android:visibility="invisible">
        <RadioGroup android:id="@+id/RadioGroup01" android:layout_height="wrap_content" android:checkedButton="@+id/RB01" android:layout_width="fill_parent">
            <RadioButton android:id="@+id/RB01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:button="@drawable/DR01"/>
            <RadioButton android:id="@+id/RB02" android:layout_width="fill_parent" android:layout_height="wrap_content" android:button="@drawable/DR02"/>
            <RadioButton android:id="@+id/RB03" android:layout_width="fill_parent" android:layout_height="wrap_content" android:button="@drawable/DR03"/>
            <RadioButton android:id="@+id/RB04" android:layout_width="fill_parent" android:layout_height="wrap_content" android:button="@drawable/DR04"/>
        </RadioGroup>
    </LinearLayout>
    </RelativeLayout>
2个回答

7

如果您想设置LinearLayout、RadioGroup或RadioButton的宽度,使用dp(独立像素密度)可能很有用。根据您上面所说的,我认为它必须是布局的宽度。这些尺寸是“硬编码”的,但它们会随着屏幕大小而缩放。

因此,xml可能如下所示:

android:layout_width="55dp"

官方的dps文档在这里


3
为什么要用 55 dp?所有安卓设备的宽度都是 220dp 吗? - Jaseem

2
我无法想象为什么其他答案有6个赞,它完全是错误的。
尺寸是“硬编码”的,但它们会随着屏幕大小而缩放。
不,它们将根据您屏幕的密度进行缩放。我非常希望我们可以使用XML中的百分比,而不必编写它们。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接