3

I'm just getting started with android development and I need help with background images. I want to be able to have a background image and then overlay other items (buttons, text, etc.) on top of that background with a layout. I used a LinearLayout just for the sake of being simple and because I don't know what's best for me at the moment.

Anyways, I can't get an image to display using the following code:

import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.*;

public class NewGameActivity extends Activity {


    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LinearLayout ll = new LinearLayout(this);
    ll.setBackgroundDrawable(Drawable.createFromPath("/assets/images/androidBackground.png"));
    this.setContentView(ll);
    }
}

2 Answers 2

4
ll.setBackgroundResource(R.drawable.image_name);

http://developer.android.com/reference/android/view/View.html#setBackgroundResource%28int%29

This is the preferred way of accessing drawable resources. The image_name is a png image in your drawable or drawable-mdpi folder.

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

1 Comment

Thank you, I just figured out how to do it in XML as well.
1

yes if you are using XML then find the id of that linearlayout like

ll=(LinearLayout)findViewById(R.id.linear1)

Then set its background as

ll.setBackgroundResource(R.drawable.image_name);

else here as your code given here you can directly go for

ll.setBackgroundResource(R.drawable.image_name);

Comments

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.