getLayoutParmas报错NullPointException

今天在写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。




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值