今天在写Android时,想改变XML中已存在控件的宽度让它有屏幕宽度1/3时,用到了child.getLayoutParmas时一直发生空指针异常,照着网上的代码写的,百度了一天,别人都是setLayoutParmas出错,最后在Google中找到了问题所在。
public void selectedLineWidth() {
DisplayMetrics dpMetrics = new DisplayMetrics();
getWindow().getWindowManager().getDefaultDisplay().getMetrics(dpMetrics);
screenWidth = dpMetrics.widthPixels;//获取屏幕宽度
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)selected_Line.getLayoutParams();//获取要改变控件的参数,在这里一直报NullPointException
lp.width = screenWidth / 3;//控件参数设置为屏幕宽度的1/3
selected_Line.setLayoutParams(lp);//设置控件参数
}
在onCreate方法中调用该方法,一直报错,最后在Google中别人提到了把getLayoutParmas放在onAttachToWindow()方法中,试了一下,果然可以,终于不报错了o(∩_∩)o
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
selectedLineWidth();
}
发现问题所在后,我去百度了一下,为什么onCreate方法中获取不到LayoutParmas,而只能在onAttachToWindow方法中就能获取?
先看以下生命周期,注意到onAttachToWindws方法在onResume方法之后,别人说Adnroid设置参数时调用了onResume()方法,也就是在onResume()之后才能获得参数,而onAttachToWindow()方法在onResume之后,而onCreate方法在onResume之前,所以onAttachToWindws()方法能获取参数,而onCreate获取参数会报NullPointException。