Fragment中测量宽度、高度, Caused by: java.lang.IllegalArgumentException: width and height must be > 0

26 篇文章 1 订阅

  在Fragment中测量控件的宽高,报错  Caused by: java.lang.IllegalArgumentException: width and height must be > 0:


对于Fragment可以采用下面的方法:

1. 使用 ViewTreeObserver 提供的 Hook 方法。
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_welcome);
    myButton = (Button) findViewById(R.id.button1);
    
    // 向 ViewTreeObserver 注册方法,以获取控件尺寸
    ViewTreeObserver vto = myButton.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        public void onGlobalLayout() {
            int h = myButton.getHeight();
            Log.i(TAG, "Height=" + h); // 得到正确结果
 
            // 成功调用一次后,移除 Hook 方法,防止被反复调用
            // removeGlobalOnLayoutListener() 方法在 API 16 后不再使用
            // 使用新方法 removeOnGlobalLayoutListener() 代替
            myButton.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        } 
    });
    
    // ...
}
该方法在 onGlobalLayout() 方法将在控件完成绘制后调用,因而可以得到正确地结果。该方法在 Fragment 中,也可以使用。




解决办法:


//  ViewTreeObserver 注册方法,以获取控件尺寸
final ViewTreeObserver vto = iv_two_code.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    public void onGlobalLayout() {
       int height = iv_two_code.getHeight();
       int width = iv_two_code.getWidth();



        //                Log.i(TAG, "Height=" + h); // 得到正确结果

        // 成功调用一次后,移除 Hook 方法,防止被反复调用
        // removeGlobalOnLayoutListener() 方法在 API 16 后不再使用
        // 使用新方法 removeOnGlobalLayoutListener() 代替
        iv_two_code.getViewTreeObserver().removeGlobalOnLayoutListener(this);
    }
});




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一个小狼娃

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值