<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/ly_keyboard_btn_Area_3"
  android:layout_above="@+id/ly_keyboard_btn_Area_2"
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content">
    <Button android:id="@+id/btn_keyboard_7"
     android:text="@string/btn_click_me" 
     android:layout_weight="1"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"/>
    <Button android:id="@+id/btn_keyboard_8"
     android:text="@string/btn_click_me" 
     android:layout_weight="1"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"/>
    <Button android:id="@+id/btn_keyboard_9"
     android:text="@string/btn_click_me" 
     android:layout_weight="1"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"/>
    </LinearLayout>
这个是XML资源文件的内容,我想定义一行,里面放3个按钮,填满。
按钮要为正方形,因为不同手机的屏幕大小是不一样的,所以button的高度,必须在代码里面设置。我的思路是界面加载完成后,得到按钮的宽度,然后将按钮的高度设置为跟按钮的宽度一样,这样按钮就是正方形了,可是遇到一个问题。
 /**初始化控件的大小*/
    @Override
    public void onResume()
    {
     super.onResume();
     LayoutParams btnPara = btn.getLayoutParams();
     btnPara.height = btnPara.width;//将按钮设置为正方形
     btn.setLayoutParams(btnPara.height);
    }
这个里面我得到的btnPara.width是-2,不是实际的宽度。这是为什么?不知道哪位大侠知道有设么办法可以获取按钮的宽度?

解决方案 »

  1.   

    因为你的组件设置的是wrap_content,对应的常量ViewGroup.LayoutParams.WRAP_CONTENT值是-2,如果你用的是fill_parent就会发现值是-1~
    你用getWidth()可以拿到宽度,不过必须要在初始化完毕后,初始化完毕之前getWidth得到的是0.因为在activity的onResume方法执行完毕后才执行各个组件的onSizeChanged方法各组件大小才改变。之前一直是0.
    比如说如果你在onResume打印btn.getWidth(),第一次进入的时候是0,然后你按home键再进入,界面之前已经初始化完毕了,这时打印的就会是正确的值~有个思路就是你写个MyButton继承Button。重写onSizeChanged方法,在onSizeChanged方法里把protected void onSizeChanged(int w, int h, int oldw, int oldh) 第一个参数通过广播或者handler或别的什么方式发给Activity。Activity中接收到宽度之后再做你想要的操作。不过我貌似记得组件大小确定后,再去改变大小会报错来着~记不清楚了~