android中的layoutinflater nullpointerexception

时间:2013-10-18 12:38:59

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

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

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

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

你没有说明'这个'是什么,或NPE正在发生的地方 - 但可能是'这个'提出了错误的背景。 请尝试使用您的活动名称?例如,MainActivity.this

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

答案 2 :(得分:0)

更改

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

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