Android XML 中有没有办法将一排按钮的宽度设置为最宽按钮?
有没有办法在XML中声明一行按钮,使所有按钮具有相同的宽度,等于最宽按钮的wrap_content宽度?我熟悉将所有宽度设置为 0 并将它们的权重全部分配为 1 的技巧,但如果父布局宽度设置为wrap_content,则这将不起作用。我不想将父级宽度设置为 fill_parent,因为我不希望按钮拉伸得超过必要的程度。
我能想到的唯一方法是在代码中(或者使用每个按钮中与其他按钮通信的 onMeasure 逻辑,或者使用自定义布局类)。
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 widest 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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为你必须在代码中做到这一点。
创建自定义布局类将是一种可行的方法。重写 onMeasure() 并使其看起来像这样:
这应该有效,但我不会把我的声誉押在上面...如果不行的话,我很乐意为您提供进一步的帮助。
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:
That should work but I won't stake my reputation on it... happy to help you further if it doesn't.
要让按钮在 XML 中排成一行,您需要在 LinearLayout 中添加按钮并将方向更改为水平,
即至于获得最宽的按钮并更改所有其他按钮以匹配,我不确定您是否会这样做您的活动中必须有某种方法来获取最宽的按钮,然后以编程方式将所有其他按钮设置为相同。
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.
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.
只需找出最宽的按钮是什么,但它在水平宽度相匹配的视图中,然后在 << 中使用layout_width =“match_parent”或“fill_parent” 2.3.
这将使它们全部使用指定的宽度。
如果您想以编程方式执行此操作,则需要迭代所有部分,找到最大值,然后再次迭代并设置它。
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.