安卓按钮等宽

5
我需要有两个按钮,可以包裹内容但始终保持相同的宽度。

enter image description here

我希望按钮1能够延伸至与按钮2相同的宽度。或者如果按钮1更宽,我需要按钮2延伸至与按钮1相同的宽度。

enter image description here

我该如何实现这个?我尝试使用LinearLayout和权重,但只有在线性布局的宽度匹配父容器时才有效,这会使按钮变得不必要地宽。

你想要水平方向还是垂直方向的? - Harsh Patel
你尝试过获取按钮2的宽度并设置按钮1的宽度吗? - Vishal G. Gohel
我希望它们水平排列,如果可能的话,希望只使用XML来完成此操作。 - antanas_sepikas
如果两个等宽的按钮没有足够的空间,应该怎么办?是让“按钮1”变小以适应“按钮2”中的长文本,还是让“按钮2”的文本省略以保持按钮宽度的1:1比率? - Bartek Lipinski
只要在有足够的空间时它们保持相同的宽度,任何一种选项都可以。 - antanas_sepikas
5个回答

3

试试这个!!! 这可能会有所帮助...

<LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:weightSum="2">

            <Button
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Button 1"/>

            <Button
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Button 2"/>
    </LinearLayout>

这将会输出如下结果:

enter image description here


在我看来,这应该是接受的答案。顺便说一下,在父LinearLayout中你不需要weightSum。 - Jorn Rigter

3

使用线性布局权重属性 首先将两个按钮包含在线性布局中,并使它们具有水平方向。 然后给它们相等的权重。

android:layout_weight="1"

尝试这个结果


2
为了使两个按钮完全相同,您需要像这样计算两个按钮的宽度。
ViewTreeObserver vto1 = button1.getViewTreeObserver();
vto1.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {

        width = button1.getWidth();
        height = button1.getHeight();
    }
});

ViewTreeObserver vto2 = button2.getViewTreeObserver();
vto2 .addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {

        width = button2.getWidth();
        height = button2.getHeight();
    }
});

然后比较两个按钮的高度,并将较大的高度设置为两个按钮的高度。

2
虽然Ajay的回答是正确的,但是在完成后需要删除监听器。
ViewTreeObserver vto2 = button2.getViewTreeObserver();
vto2 .addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {

        width = button2.getWidth();
        height = button2.getHeight();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            myView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
        else {
            myView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        }
    }
});

如果您正在使用Dialog,您可以使用dialog.setOnShowListener,并在其中获取/设置按钮的大小。 - MatJB

0

我来回答一个老问题,但是有一个一行的解决方案。

在 XML 文件中,将 android:layout_width="0dip" 添加到所有按钮定义中。

另一个(替代)解决方案是在所有按钮定义中添加 android:layout_width="fill_parent"


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