Is there a way to declare a row of buttons in XML so that all the buttons have the same width, which is equal to the wrap_content width of the wid开发者_JAVA技巧est button? I'm familiar with the trick of setting all the widths to 0 and assign them all a weight of 1, but that won't work if the parent layout width is set to wrap_content. I don't want to set the parent width to fill_parent because I don't want the buttons stretched more than necessary.
The only way I can think of doing this is in code (either with onMeasure logic in each button that communicates with the other buttons or with a custom layout class).
I think you'd have to do this in code.
Creating a custom layout class would be the way to go. Override onMeasure() and make it look something like this:
- Call setLayoutParams on all children to set their layout_widths to WRAP_CONTENT.
- Call super.onMeasure()
- Iterate child views to find the one with the biggest getMeasuredWidth().
- Iterate all other child views calling setLayoutParams() with the widest pixel width.
- Call super.onMeasure() again. :)
That should work but I won't stake my reputation on it... happy to help you further if it doesn't.
To get the buttons in a row in the XML you need to add the buttons with in a LinearLayout and change the orietnation to horizontal i.e.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
</LinearLayout>
As for getting the widest button and changing all the other buttons to match I am not sure as a guess you would have to have some sort of method within your activity to get the widest button and then programaticaly set all the other buttons to be the same.
Just find out what your widest button is, but it in a view with a horizontal width to match, and then use layout_width="match_parent" or "fill_parent" in < 2.3.
It'll make them all use the width assigned.
If you want to do it programatically, you need to iterate over all the sections, find the max, than iterate again and set it.
精彩评论