Inset drawable not working as described in documentation

谁说我不能喝 提交于 2020-01-01 04:53:25

问题


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>



回答3:


Another option: if you want to use DP instead of PX, try my suggestion below. From my experience, InsetDrawable only works with pixels, which I find... unhelpful. To be honest, I am not happy with this solution, but hey, it works.

<?xml version="1.0" encoding="utf-8"?>
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android">

<item
        android:bottom="10dp"
        android:drawable="@drawable/image_placeholder"
        android:top="10dp" />
</layer-list>


来源:https://stackoverflow.com/questions/26850400/inset-drawable-not-working-as-described-in-documentation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!