Buttons should be as wide as the biggest

android, android-layout, android-view, view

Solution

Wrap, all the button inside a common parent Say linearlayout having attributes as wrap_content, wrap_content. use the attributes Match_Parent for your button, now programmatically you just calculate the size of biggest text and set it as parent width, and call layout over it, this will make sure all the child it contains gets resized efficiently.

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

Problem

I want all `Button` to fit the text, so there is no line breaks in the `Button`s, but also all the `Button` should has the same width: as wide as the biggest. I achieved this with setting all the `Button` `layout_width`'s to be `WRAP_CONTENT` in the layout: ``` <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> ``` Then i search for the biggest value, and set all the buttons to be same sized: ``` @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); } } ``` Is there any cleaner, more elegant solution for this?

Original source