android - 为什么相同的 layout_weight 导致 Android ImageButton 和 Button 的宽度不同?

标签 android android-layout android-imagebutton android-layout-weight

当我尝试将常规 Button 和 ImageButton 设置为相同的 layout_weight 时,我的 LinearLayout 出现一些奇怪的行为。图像按钮的 android:src 资源非常小,可以很好地放入 ImageButton 中,没有任何问题。尽管它们的宽度应该相同,但出于某种原因,ImageButton 的宽度大约是其余普通按钮大小的 2/3。如果我将 ImageButton 的 layout_weight 乘以 10,它会更接近正确的大小,但为什么这不起作用?

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_weight="1">
    <Button
            android:id="@+id/clear"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/clear"/>
    <Button
            android:id="@+id/left_paren"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/left_paren"/>
    <Button
            android:id="@+id/right_paren"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/right_paren"/>
    <ImageButton
            android:id="@+id/backspace"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:adjustViewBounds="true"
            android:contentDescription="@string/backspace"
            android:src="@drawable/backspace"/>
</LinearLayout>

最佳答案

您需要为所有应具有相同宽度的按钮设置 android:layout_width="0dp"。 (更准确地说,您需要为所有这些按钮设置相同的 layout_width0dp 是要使用的常规宽度。使用相同的权重时,只要还有额外的空间分配,您使用的实际宽度与结果无关。)layout_weight 仅确定在按钮占用指定宽度后如何分配剩余空间。因此,如果它们开始时不相等(宽度为 wrap_content),它们在考虑权重后仍然不同。

关于android - 为什么相同的 layout_weight 导致 Android ImageButton 和 Button 的宽度不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41582405/

相关文章:

android - 菜单目录丢失

安卓 WebView : Remove pop-out option in google drive/doc viewer

android - 在 Android 中设置选中/选中的图像按钮

android - 带有图标或图像的 ImageButton 中未显示文本

android - 如何防止我的应用程序在使用 JSON 数据时意外崩溃 "force close"并改为处理异常?

android - 如何显示我的相机预览

android - 使用 XML 中的重力或 Linear_gravity 在 LinearLayout 中左对齐图像

android - 如何在使用 addView 时设置 View 的位置

java - Android:如何创建一个多功能区域来交换 XML 布局文件中的不同 View

java - 关于 ImageButtons 滞后且不合适的 2 个问题