在java中设置背景图片 [英] Setting background image in java
问题描述
所以基本上,我有一个xml,我想重用。内容有些是一样的,只是背景不同,一些调整太..我该如何去做到这一点。我曾尝试 View.setBackGroundDrawable(R.drawable.sample);
,但它不工作。我的应用程序崩溃。我已经把我的形象,虽然里面的文件夹绘制的一个。
So basically, I have an xml, which i want to reuse. The content is somewhat the same, only the background is different and a few adjustment too.. How can I go about to do this.. I have tried View.setBackGroundDrawable(R.drawable.sample);
but it does not work. My app crash. I've placed my image inside one of the drawable folder though.
推荐答案
您可以尝试在你的XML分配为您布局的ID,这样在你的java code,可以为其设置不同的布局..下面是一个例子:
You can try to assign an id for your layout on your xml so that on your java code, you can set a different layout for it.. Here is an example:
//assuming your Layout is named linearlayout1:
LinearLayout ll = (LinearLayout) findViewById(R.id.linearlayout1);
ll.setBackgroundResource(R.drawable.sample);
您还可以创建,如果设置你的背景像以前一样的语句:
You can also create if statements before setting your background like:
LinearLayout ll = (LinearLayout) findViewById(R.id.linearlayout1);
if( yourifstatement) {
ll.setBackgroundResource(R.drawable.sample);
}
如果它是一个RelativeLayout的,那么同样code适用,只是改变的LinearLayout到RelativeLayout的。
If it is a RelativeLayout, then the same code applies, just change LinearLayout to RelativeLayout.
如果这不是问题,请发表您的LogCat中。
If this is not the problem, please post your LogCat.
这篇关于在java中设置背景图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!