4

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.

6
  • 2
    What error messages you got from the crash? Commented Nov 15, 2012 at 2:51
  • Instrumentation.callActivityOnCreate(Instrumentation... .java:1053) Commented Nov 15, 2012 at 2:56
  • could you paste the stack trace from your logcat? Commented Nov 15, 2012 at 2:58
  • com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(Zygo ... .java:993) this look totally foreign.. Commented Nov 15, 2012 at 2:58
  • @Sahara : what view is it? is it an image view, button etc? Commented Nov 15, 2012 at 3:03

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Can you explain the LinearLayout ll = (LinearLayout) findViewById(R.id.linearlayout1); why is it R.id.. instead of R.layout
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);
@Sahara - And also, your LinearLayout is only a part of the xml that you would like to re-use.
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.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.