我想在一行中绘制两个Button
s,宽度相等。比如,他们有标题:“示例文本”和“额外文本”。它们应占据尽可能低的空间,但所有的单词都应该写出来。
我写了这段代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:maxLines="1"
android:text="Sample text"
android:textAllCaps="false" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:maxLines="1"
android:text="Extra text"
android:textAllCaps="false" />
</LinearLayout>
如果我删除android:maxLines="1"
并将wrap_content
设置为width,Button
s会写一个文本,但填充不同的宽度。
如果要在一行上找到两个按钮,则需要将match_parent
设置为layout_width
的LinearLayout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:maxLines="1"
android:text="Sample text"
android:textAllCaps="false" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:maxLines="1"
android:text="Extra text"
android:textAllCaps="false" />
</LinearLayout>
为两个按钮添加布局权重。因此,它将确保您具有相同的尺寸。
android:layout_weight="1"
同时获取屏幕大小并以编程方式设置大小。
修复特定按钮大小将影响小尺寸屏幕。
让你想调整第二个按钮的大小。
如果按钮包含图标,请将其与How to center icon and text in a android button with width set to "fill parent"对齐。例如,在Button
内移动FrameLayout
或用LinearLayout
和ImageView
创建TextView
。
如果您的案例是自定义视图,而按钮是带图标的FrameLayout
,请覆盖以下事件:
boolean isButtonResized;
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
if (!isButtonResized) {
int buttonWidth = firstButton.getWidth();
if (buttonWidth != 0) {
isButtonResized = true;
ViewGroup.LayoutParams lp = secondButton.getLayoutParams();
lp.width = buttonWidth;
secondButton.setLayoutParams(lp);
}
}
}
如果你有一个没有图标的按钮,只有文本,调整大小会更简单:
secondButton.setWidth(firstButton.getWidth());