android 4.3 调用 view.measure()时报空指针异常

Android开发中遇到调用
view.measure(int widthMeasureSpec, int heightMeasureSpec)
这个函数时,如果这个View是通过LayoutInflater来构建的,例如:

view = LayoutInflater.from(mContext).inflate(
                    R.layout.xxx, null);

会报:
java.lang.NullPointerException
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:529)
at android.view.View.measure(View.java:15676)
这个问题只有在Android4.3版本才会出现
原因如下:
如果使用Inflater的情况下会出现以上错误,原因是用Inflater渲染组件的时候并没有给其指定父控件,所以渲染器不会去解析width 和 height属性,就会导致空指针异常。
解决办法:
在view.measure(int widthMeasureSpec, int heightMeasureSpec)之前加上以下代码,为其指定宽度和高度即可

view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

猜你喜欢

转载自blog.csdn.net/caijinghuacaijinghua/article/details/78413963
4.3