Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting background image in java

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.

like image 938
Becky Reyna Avatar asked Jan 15 '23 00:01

Becky Reyna


1 Answers

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);
}

If it is a RelativeLayout, then the same code applies, just change LinearLayout to RelativeLayout.

If this is not the problem, please post your LogCat.

like image 151
omi0301 Avatar answered Jan 21 '23 18:01

omi0301