考虑到 wrap_content 属性后,如何获取按钮大小?
我想创建 2 个大小相同的按钮,它们都具有 wrap_content 属性,所以我的解决方案是使用 wrap_content 创建它们,获取最大宽度和高度,并将最大值应用于两个按钮,问题是我尝试打印按钮的宽度和高度时,我只得到零值。
//Create the first button
Button firstButton= new Button(activity);
LinearLayout.LayoutParams secondaryParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f);
footerLayout.addView(firstButton, firstParams);
//same thing for the other button
Button secondaryButton= new Button(activity);
LinearLayout.LayoutParams secondaryParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f);
footerLayout.addView(secondaryButton, 0, secondaryParams );
//trying to get the size:
firstButton.measure(0, 0); //must call measure!
int measuredWidth = firstButton.getWidth();
int measuredHeight = firstButton.getHeight();
在应用 WRAP_CONTENT 属性后,获取 2 个按钮的大小。