android:按钮的宽度相当于最宽的按钮
问题描述:
我有两个按钮放在布局内部。我想'他们有相同的宽度。但每个按钮的宽度必须等于其中最宽的那个。现在我使用ViewTreeObserver。android:按钮的宽度相当于最宽的按钮
class LayoutListener implements ViewTreeObserver.OnGlobalLayoutListener{
private Button btn1, btn2;
public LayoutListener(Button b1, Button b2){
btn1 = b1; btn2 = b2;
}
@Override
public void onGlobalLayout() {
int w1 = btn1.getWidth();
int w2 = btn2.getWidth();
if (w1 < w2)
btn1.setWidth(w2);
else
btn2.setWidth(w1);
}
}
但它不是很好的决定becase元素被显示给用户后重绘,它看起来很可怕。 和你可以猜测的问题,我如何达到需要的行为?有没有标记操作的方式,或者我应该实现特殊的代码?最好避免创建可用作按钮容器的自定义布局。
答
如果我在呼叫后直接呼叫getWidth
它总是返回0. 为了防止它在获取大小之前我应该使用measure
函数初始化测量过程。 这是我的代码(但我不知道这是最好和最快的方法))):
....
view = inflator.inflate(R.layout.send_command_item, null);
btnOff = (Button)view.findViewById(R.id.btnOff);
btnOn = (Button)view.findViewById(R.id.btnOn);
set_w(btnOff, btnOn);
.....
public void set_w(Button btn1, Button btn2) {
btn1.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
btn2.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
int w1 = btn1.getMeasuredWidth();
int w2 = btn2.getMeasuredWidth();
if (w1 < w2)
btn1.setWidth(w2);
else
btn2.setWidth(w1);
}
答
您可以比较活动的onCreate()方法中的按钮宽度,然后设置它们,还是需要在不同的时间更改它们的大小?
编辑:
后您虚增您的看法,您可以创建两个Button变量和使用(Button)yourViewName.findViewById(R.id.buttonid);
约束他们。然后,您可以使用getWidth()和setWidth()根据需要进行比较和修改。
我创建视图:视图= inflator.inflate(R.layout.list_view_item,空),并不能赶上创建方法。除此之外,如果我没有弄错(我是android开发中的新手),只有在onMesure方法中才有可能获得计算大小,不是。 – DotNetter
按钮是否在xml文件中定义? – Nate
对于迟到的回答感到抱歉。我需要搁置我的android项目一段时间。我尝试了你的建议:看到我在这个主题的答案 – DotNetter