我希望所有内容都Button
适合文本,因此Button
s中没有换行符,但是所有Button
宽度都应该相同:宽度最大.
我通过将所有Button
layout_width
' 设置WRAP_CONTENT
为布局来实现此目的:
...
然后我搜索最大值,并将所有按钮设置为相同大小:
@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); } }
对此有更清洁,更优雅的解决方案吗?
Wrap,普通父母中的所有按钮Say linearlayout,其属性为wrap_content,wrap_content.使用Match_Parent属性为您的按钮,现在以编程方式,您只需计算最大文本的大小并将其设置为父宽度,并在其上调用布局,这将确保它包含的所有子项都有效地调整大小.
<LinearLayout <!--Parent--> android:layout_ android:layout_ android:orientation="vertical" > <!-- Child --> <Button android:layout_ android:layout_ /> <Button android:layout_ android:layout_ /> </LinearLayout>
使用TableLayout
和TableRow
将让列(在这种情况下Button
)具有固定宽度,取决于最大/最长的列.android:shrinkColumns
用于一些Buttons
比屏幕宽度更长的单词以使单词换行.
例:
<?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_ android:layout_ android:shrinkColumns="0" > <TableRow> <Button android:text="Short" /> </TableRow> <TableRow> <Button android:text="Longer text" /> </TableRow> <TableRow> <Button android:text="Middle" /> </TableRow> </TableLayout>