按钮应该与最大的一样宽

时间:2013-12-06 08:57:35

标签: android android-layout view android-view

我希望所有Button符合文字,因此Button中没有换行符,但Button所有宽度应相同:宽度与最大。

我通过在布局中将所有Button layout_width设置为WRAP_CONTENT来实现此目的:

<LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    ...

</LinearLayout>

然后我搜索最大值,并将所有按钮设置为相同大小:

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);


    ViewGroup layout = (ViewGroup) findViewById(R.id.layout);
    int size = 0;
    for (int i = 0; i < layout.getChildCount(); ++i) {
        View child = layout.getChildAt(i);
        if (child.getWidth() > size) {
            size = child.getWidth();
        }
    }

    for (int i = 0; i < layout.getChildCount(); ++i) {
        LayoutParams params = layout.getChildAt(i).getLayoutParams();
        params.width = size;
        layout.getChildAt(i).setLayoutParams(params);
    }
}

对此有更清洁,更优雅的解决方案吗?

3 个答案:

答案 0 :(得分:6)

Wrap,普通父母内部的所有按钮Say linearlayout,其属性为wrap_content,wrap_content。使用Match_Parent属性为您的按钮,现在以编程方式,您只需计算最大文本的大小并将其设置为父宽度,并调用它的布局,这将确保它包含的所有子节点有效调整大小。

<LinearLayout  <!--Parent-->
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    <!-- Child -->
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

答案 1 :(得分:5)

使用TableLayoutTableRow会让列(在本例中为Button)具有固定宽度,取决于最大/最长的列。如果某些android:shrinkColumns长于屏幕宽度以使单词换行,则使用Buttons

示例:

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:shrinkColumns="0" >
    <TableRow>
        <Button android:text="Short" />
    </TableRow>
    <TableRow>
        <Button android:text="Longer text" />
    </TableRow>
    <TableRow>
        <Button android:text="Middle" />
    </TableRow>
</TableLayout>

答案 2 :(得分:-1)

使用Match_Parent代替Wrap_Content,如下所示..

<Button
android:layout_width="match_parent"
android:layout_height="match_parent" />

<Button
android:layout_width="match_parent"
android:layout_height="match_parent" />

希望这有帮助!!!