How to implement an android:background that doesn't stretch?
I found this great thread describing how to "eat the cake and have it too", i.e. use image for a Button
instead of ImageButton
(which doesn't allow SetText()
, resizing, etc.).
This is achieved by using the View attribute:
android:background="@drawable/bgimage"
The only problem with this is that it stretches the image to fit the button size.
Short of hard-coding a fixed button size (in pixels!), is there a way to tell Android not to stretch the background image at all and either crop or pad it?
Solution 1:
You can create an xml bitmap and use it as background for the view. To prevent stretching you can specify android:gravity
attribute.
for example:
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/dvdr"
android:tileMode="disabled" android:gravity="top" >
</bitmap>
There are a lot of options you can use to customize the rendering of the image
http://developer.android.com/guide/topics/resources/drawable-resource.html#Bitmap
Solution 2:
You should use ImageView if you don't want it to stretch. Background images will always stretch to fit the view. You need to set it as a Drawable to force the image aspect to the object.
Otherwise, if you are sticking with the Button idea, then you will need to force the scaling in the button to prevent the image from stretching.
Code:
onCreate(Bundle bundle) {
// Set content layout, etc up here
// Now adjust button sizes
Button b = (Button) findViewById(R.id.somebutton);
int someDimension = 50; //50pixels
b.setWidth(someDimension);
b.setHeight(someDimension);
}