Background Image Placement
I'm trying to set my root LinearLayout element (which is set to fill_parent in both dimensions) to have a background image which is always located in the lower left corner of the screen no matter the orientation of the device. It would be excellent if there were some way to set the background image position such as that which you can do with css using "background-position: left bottom;" but I'm开发者_StackOverflow not seeing a way to achieve this in Android. Is there a way to do this?
Thanks for the help.
You'll have to create a custom bitmap drawable with your bitmap in an XML file (eg "res/drawables/my_drawable.xml"
<?xml version="1.0" encoding="utf-8"?>
<bitmap
xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/my_png_file"
android:gravity="bottom|left" />
And then set this drawable xml as your view's background ("@drawables/my_drawable"). The drawable XML format is very poorly documented in the Android site, though, so it's definitely not an easy problem to figure out how to solve on your own.
If found an advantage doing this programatically: the image fits the layout instead of being bigger then it. No ideia why.
The code:
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.image);
BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp);
bitmapDrawable.setGravity(Gravity.BOTTOM|Gravity.RIGHT);
LinearLayout layout = (LinearLayout) findViewById(R.id.background_root);
layout.setBackgroundDrawable(bitmapDrawable);
Wrap your LinearLayout into a RelativeLayout and add an ImageView to it. Using android:layout_alignParentBottom and android:layout_alignParentLeft you can put your image to the lower left.
<RelativeLayout
android:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:src="@drawable/my_image" />
<LinearLayout
android:id="@+id/linearLayout"
... >
Make sure ImageView is the first element of RelativeLayout to draw the image in background.
My answer is just an update of above answers If you are using XML for background, it may occur problem in aspect ratio
so use this code
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.image);
BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp);
bitmapDrawable.setGravity(Gravity.BOTTOM| Gravity.RIGHT| Gravity.FILL_HORIZONTAL);
LinearLayout layout = (LinearLayout) findViewById(R.id.background_root);
layout.setBackgroundDrawable(bitmapDrawable);
Gravity.Fill_HORIZONTAL will fit with width of layout on which you are applying background you can also mention this in XML file but as i said it will occur issue of Image Ratio
精彩评论