两个相同宽度的按钮,一行中有几个单词

问题描述 投票:1回答:3

我想在一行中绘制两个Buttons,宽度相等。比如,他们有标题:“示例文本”和“额外文本”。它们应占据尽可能低的空间,但所有的单词都应该写出来。

现在它看起来如此:enter image description here

我写了这段代码:

<?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,Buttons会写一个文本,但填充不同的宽度。

android button
3个回答
0
投票

如果要在一行上找到两个按钮,则需要将match_parent设置为layout_widthLinearLayout

<?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>

0
投票

为两个按钮添加布局权重。因此,它将确保您具有相同的尺寸。

android:layout_weight="1"

同时获取屏幕大小并以编程方式设置大小。

Get Screen width and height

修复特定按钮大小将影响小尺寸屏幕。


0
投票

让你想调整第二个按钮的大小。

如果按钮包含图标,请将其与How to center icon and text in a android button with width set to "fill parent"对齐。例如,在Button内移动FrameLayout或用LinearLayoutImageView创建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());
© www.soinside.com 2019 - 2024. All rights reserved.