The difference between the XML attribute src and background in ImageView:
The background is stretched according to the length and width given by the ImageView component, while SRC stores the size of the original and does not stretch. SRC is the picture content (foreground), BG is the background and can be used simultaneously.
In addition:ScaleType only works on SRC; BG can set transparency, such as the ability to use Android:scaletype to control how images are scaled in ImageButton
As described above, the picture set by background is stretched with the length-to-width ratio given by the view component. For example, the 36x36 px icon is placed in the xhdpi folder, in 854x480 (FWVGA, corresponding hdpi) environment, according to
Xhdpi:hdpi:mdpi:ldip = 2:1.5:1: 0.75
FWVGA, the actual size of the icon should be 27x27.
But when I put it in a layout_width = 96px, layout_height = 75px linearlayout, the layout code is as follows:
<LinearLayoutandroid:gravity= "Center"Android:layout_width= "96px"Android:layout_height= "75px" > <ImageButtonAndroid:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:background= "@drawable/toolbar_bg"/> </LinearLayout>
The reality is that the size of the ImageButton we get is 33x27, and obviously the width is stretched, which is what we don't want to see.
Solution One:
The ImageButton layout_width and Layout_width are set dynamically in the code, as follows
New Linearlayout.layoutparams (at); Layout.addview (ImageButton, layoutparam);
However, in fact we do not want the code to have a "hard-coded" situation.
Solution Two:
When you set the Android:background property through Setbackgroundresource () or in XML, your background is defined as an XML bitmap, as follows:
<?XML version= "1.0" encoding= "Utf-8"?><Bitmapxmlns:android= "Http://schemas.android.com/apk/res/android"Android:id= "@id/toolbar_bg_bmp"android:src= "@drawable/toolbar_bg"Android:tilemode= "Disabled"android:gravity= "Top" ></Bitmap>
The call is as follows:
Imagebutton.setbackgroundresource (r.drawable.toolbar_bg_bmp)
Or
<imagebutton android:background= "@drawable/toolbar_bg_bmp" .../>
If the background image has a variety of states, you can also refer to Toolbar_bg_selector.xml:
<?XML version= "1.0" encoding= "Utf-8"?><selectorxmlns:android= "Http://schemas.android.com/apk/res/android" > <Itemandroid:state_pressed= "true" > <Bitmapandroid:src= "@drawable/toolbar_bg_sel"Android:tilemode= "Disabled"android:gravity= "Top" /> </Item> <Item> <Bitmapandroid:src= "@drawable/toolbar_bg"Android:tilemode= "Disabled"android:gravity= "Top" /> </Item></selector>
So, no matter whether the background is set in code mode Setbackgroundresource () or XML android:background, no stretch is produced.
This article transferred from: http://blog.csdn.net/oathevil/article/details/23707359