The buttons should be as wide as the largest

I want all Button match the text, so there are no line breaks in Button s, but all Button should be the same width: as wide as the largest.

I achieved this with setting in 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> 

Then I search for the biggest value and set all buttons of the same size:

 @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); } } 

Are there any cleaner, more elegant solutions for this?

+7
android android-layout view android-view
source share
3 answers

Wrap all buttons inside a common parent. Say linearlayout has attributes like wrap_content, wrap_content. use the Match_Parent attributes for your button, now programmatically you simply calculate the size of the largest text and set it as the parent width, and also lay out above it, this ensures that all of its child will be effectively resized.

 <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> 
+6
source share

Using TableLayout and TableRow , let the column (in this case, Button ) have a fixed width, depending on the largest / longest. android:shrinkColumns used if some of the Buttons longer than the screen width to wrap words.

Example:

 <?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> 
+4
source share

Use MatchParent instead of WrapContent as shown below.

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

Hope this helps !!!

-one
source share

All Articles