当我尝试将常规 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_width
,0dp
是要使用的常规宽度。使用相同的权重时,只要还有额外的空间分配,您使用的实际宽度与结果无关。)layout_weight
仅确定在按钮占用指定宽度后如何分配剩余空间。因此,如果它们开始时不相等(宽度为 wrap_content
),它们在考虑权重后仍然不同。
关于android - 为什么相同的 layout_weight 导致 Android ImageButton 和 Button 的宽度不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41582405/