Android stretch background image of a switch button

I have a Toggle button like:

<ToggleButton android:id="@+id/tv_pmpSwitch" android:layout_width="0dp" android:layout_weight="0.1" android:layout_height="wrap_content" android:background="@drawable/toggle_view" android:layout_gravity="center_vertical" android:gravity="center" android:textOn="" android:textOff="" android:focusable="false" android:focusableInTouchMode="false" android:layout_centerVertical="true" android:paddingTop="16dp" android:layout_marginLeft="16dp" /> 


And my toggle_view is available:

 <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- When selected, use grey --> <item android:drawable="@drawable/ic_list_action" android:state_checked="true" /> <!-- When not selected, use white--> <item android:drawable="@drawable/ic_grid_action" android:state_checked="false"/> </selector> 


I don’t understand why the background image is stretched? I tried images of different sizes.

+4
source share
3 answers

After trying a few things, I found that not so:
WeightSum was the culprit, and the assigned weight stretched the image.

 <LinearLayout android:layout_width="0dp" android:layout_weight="0.1" android:layout_height="wrap_content"> <ToggleButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tv_pmpSwitch" android:background="@drawable/ic_toggle_list" /> </LinearLayout> 


Entering all the code inside the LL parent did the trick

+2
source
 <ToggleButton android:id="@+id/tv_pmpSwitch" android:layout_width="0dp" android:layout_height="28dp" android:layout_weight="0.1" android:background="@drawable/toggle_view" android:textOff="" android:textOn="" /> 

Try this on your code and adjust only the layout height parameter!

EDIT

The way to get an unstretched image is to use a bitmap, not a drawing. use the following as your xml as background.

 <?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item > <bitmap android:src="@drawable/ic_list_action" android:gravity="center_vertical|left" /> </item> <item> <bitmap android:src="@drawable/ic_grid_action" android:gravity="center_vertical|left" /> </item> </layer-list> 
+8
source

You can simply install in the xml layout file:

 android:minWidth="0dp" android:minHeight="0dp" 

Image will no longer stretch

+2
source

All Articles