在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); } });