【问题标题】:layoutinflater nullpointerexception in androidandroid中的layoutinflater nullpointerexception
【发布时间】:2013-10-18 12:38:59
【问题描述】:

我想在FrameLayout 中设置Activity。这是我的代码:

FrameLayout fl = new FrameLayout(this);
fl = (FrameLayout ) findViewById(R.id.actioncontent);           
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);           
View myview =LayoutInflater.from(this).inflate(R.layout.wallpaper, null);
fl.removeAllViews();
fl.addView(myview);

我收到一个错误 NullPointerException

【问题讨论】:

  • 查看 myview =LayoutInflater.from(this).inflate(R.layout.wallpaper, null);将其更改为 View myview =inflater.inflate(R.layout.wallpaper, null);
  • 谢谢你,我明白了我解决了这个错误现在我有另一个问题我想在这个框架布局中显示一个活动,活动名称是壁纸我如何在框架布局中显示这个活动

标签: java android nullpointerexception layout-inflater android-framelayout


【解决方案1】:

您需要使用inflator 而不是LayoutInflater.from(this)

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View myview =LayoutInflater.from(this).inflate(R.layout.wallpaper, null);
            fl.removeAllViews();
                fl.addView(myview);

将上面的代码替换为下面的代码

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View myview =inflater .inflate(R.layout.wallpaper, null);
            fl.removeAllViews();
                fl.addView(myview);

【讨论】:

    【解决方案2】:

    改变

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    

    LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    

    【讨论】:

      【解决方案3】:

      您没有说明 'this' 是什么,或者 NPE 发生在哪里 - 但可能是 'this' 呈现了错误的上下文。 尝试改用您的活动名称?比如MainActivity.this

      另外,如下所述,将View myview =LayoutInflater.from(this).inflate 替换为View myview = inflater.inflate

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-09
        • 1970-01-01
        相关资源
        最近更新 更多