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.setBackgroundD开发者_开发问答rawable(Drawable.createFromPath("/assets/images/androidBackground.png"));
this.setContentView(ll);
}
}
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.
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);
精彩评论