Inset drawable not working as described in documen

2019-03-25 16:03发布

问题:

As described on Android Developer site:

A drawable defined in XML that insets another drawable by a specified distance. This is useful when a View needs a background that is smaller than the View's actual bounds.

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

Instead of just moving the background and leaving the content in place in my case the inset is also moving the TextView.

This is the layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/bg_inset"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/text1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Some text"
            android:textSize="23sp" />

    </LinearLayout>

This is the bg_inset drawable

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@android:color/darker_gray"
    android:insetLeft="100dp" />

And this is the result I get:

回答1:

By default, setting a background drawable also applies that drawable's padding to the view. Set the padding explicitly if you don't want it to match the background drawable.



回答2:

Try to use shape with left-padding instead of inset:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <solid android:color="@android:color/darker_gray"/>
    <padding android:left="100dp"/>
</shape>