简体   繁体   中英

How to apply a background only for the drawable portion of a textview in Android?

I have a textview in a layout which has drawable set (leftDrawable). I would like to have a background applied to only the drawable portion and the text should appear outside of the background. Is this possible?

You could try a Layer List with a Shape Drawable as a background.

http://developer.android.com/guide/topics/resources/drawable-resource.html#LayerList

http://developer.android.com/guide/topics/resources/drawable-resource.html#Shape

For example, in your layout you could have a TextView like this:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:drawableLeft="@drawable/left"
    android:text="Hello world!" />

The drawable references drawable/left.xml which contains your layer-list:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/background"/>
    <item android:drawable="@drawable/ic_launcher"/>
</layer-list>

The icon to display can be any drawable, here the launcher icon for test purposes. The background drawable is defined in drawable/background.xml , which contains a shape:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <size
        android:height="48dp"
        android:width="48dp" />
    <solid android:color="#ffff0000" />
</shape>

Your background doesn't have to be a shape of course, it can be any other drawable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM