2016-11-04 136 views
-2

我为LinearLayout背景创建了Drawable资源文件。我使用,在LinearLayout上调用setBackground时发生NullPointerException

Drawable d = getResources().getDrawable(R.drawable.theme_default_bg); 
layoutBackground.setBackground(d); 

layoutBackgroundLinearLayout设置可绘制在MainActivity。但是,当我运行它时,它返回一个NullPointerException。我该如何解决这个问题?

编辑 我在main.xml文件中设置了xml背景,它工作。我当我试图从MainActivity.java

+0

大概layoutBackground为null –

+0

您的layoutBackground未正确初始化我认为。 – Sayem

+0

让我们看看你如何在代码中设置layoutBackground,以及如何将它设置为布局为 –

回答

0

我发现了错误。我很抱歉,我尝试setBackground的布局是在另一个布局文件(activity_main.xml)中。所以我用一个LayoutInflater,

LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View mainView = inflater.inflate(R.layout.activity_main, null); 

layoutBackground = (LinearLayout)mainView.findViewById(R.id.layout_bg); 

现在错误解决了。我很抱歉,我浪费了你的时间。我真的很抱歉。

1

试试这个......你的情况,你有没有初始化的layoutBackground设置背景此错误..

RelativeLayout layoutBackground =(RelativeLayout)findViewById(R.id.background); 

Drawable d = getResources().getDrawable(R.drawable.theme_default_bg); 

layoutBackground.setBackgroundResource(d); 
+0

的XML。谢谢。对不起,我没有在这里打它,但我初始化布局。 – Malinda

+0

尝试在调试时运行它并找到问题 –

1

只需使用:

layout.setBackgroundResource(R.drawable.theme_default_bg); 

而不是试图将资源转换为可绘制。

+0

谢谢。我尝试过,但我仍然NullPointException。 – Malinda

+0

你有初始化布局吗?如layout =(LinearLayout)findviewbyid(.....); – MichaelStoddart

+0

是@MixhaelStoddart – Malinda

相关问题