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.
-
2What error messages you got from the crash?Don– Don2012-11-15 02:51:23 +00:00Commented Nov 15, 2012 at 2:51
-
Instrumentation.callActivityOnCreate(Instrumentation... .java:1053)Becky Reyna– Becky Reyna2012-11-15 02:56:57 +00:00Commented Nov 15, 2012 at 2:56
-
could you paste the stack trace from your logcat?Robin Chander– Robin Chander2012-11-15 02:58:25 +00:00Commented Nov 15, 2012 at 2:58
-
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(Zygo ... .java:993) this look totally foreign..Becky Reyna– Becky Reyna2012-11-15 02:58:39 +00:00Commented Nov 15, 2012 at 2:58
-
@Sahara : what view is it? is it an image view, button etc?Ashwin– Ashwin2012-11-15 03:03:24 +00:00Commented Nov 15, 2012 at 3:03
|
Show 1 more comment
1 Answer
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.
5 Comments
Becky Reyna
Can you explain the LinearLayout ll = (LinearLayout) findViewById(R.id.linearlayout1); why is it R.id.. instead of R.layout
omi0301
Because you are naming your LinearLayout on your activity. Your not yet setting the content (which is used for xml. Linear Layout is just a part of an xml). You are setting the background of the layout on ll.setBackgroundResource(R.drawable.sample);
omi0301
@Sahara - And also, your LinearLayout is only a part of the xml that you would like to re-use.
Becky Reyna
i dont get it.. why am i creating a new layout??when I already have an xml but my xml has no background image and i want to set the image in the java class.. so that I can reuse that same xml in my other java class by just using different background image but with same xml.
omi0301
@Sahara - The answer above only shows how to set an image background for 1 xml that can be used on different activities. It is not to create a new layout.