I am using Eclipse to write an Android app. I want my app to display a background image which is stretched to the size of the screen.
I have written the following code, but in the emulator it immediately exited the app when I ran it. Could someone please help me to understand the problem...
Here is my code...
public class Roller extends Activity {
Display display = getWindowManager().getDefaultDisplay();
int dwidth = display.getWidth();
int dheig开发者_如何学Pythonht = display.getHeight();
Bitmap background1 = BitmapFactory.decodeResource(getResources(),R.drawable.sunnybackground);
Bitmap BSunny = Bitmap.createScaledBitmap(background1,dwidth,dheight,true);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(new Panel(this));
}
class Panel extends View {
public Panel(Context context) {
super(context);
}
public void onDraw(Canvas canvas) {
canvas.drawBitmap(BSunny, 0, 0, null);
}
}
}
Why not just something like this:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
ImageView iv = new ImageView(this, null);
iv.setBackgroundResource(R.drawable.sunnybackground);
setContentView(iv);
}
Why don't you set the background image in the layout xml file? Do you have to set it programmatically at runtime?
I think you do as below (It seems that you can't get display info unless activity is created)
public class Roller extends Activity {
Bitmap BSunny;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
Display display = getWindowManager().getDefaultDisplay();
int dwidth = display.getWidth();
int dheight = display.getHeight();
Bitmap background1 = BitmapFactory.decodeResource(getResources(),R.drawable.sunnybackground);
BSunny = Bitmap.createScaledBitmap(background1,dwidth,dheight,true);
setContentView(new Panel(this));
}
class Panel extends View {
public Panel(Context context) {
super(context);
}
public void onDraw(Canvas canvas) {
canvas.drawBitmap(BSunny, 0, 0, null);
}
}
}
精彩评论