插入的可绘制对象在文档中描述的方式下无法正常工作。

11
根据安卓开发者网站上的描述:一个在XML中定义的drawable,可以将另一个drawable按指定距离缩小。当视图需要一个比实际边界小的背景时,这非常有用。此链接详细说明了InsetDrawable:http://developer.android.com/guide/topics/resources/drawable-resource.html#Inset 。在我的情况下,与其仅移动背景并保持内容不变,Inset还会移动TextView。以下是该布局:
<?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>

这是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" />

这是我得到的结果:

布局结果

3个回答

15

默认情况下,设置背景可绘制对象也会将该可绘制对象的填充应用于视图。如果您不想使其与背景可绘制对象匹配,请显式地设置填充。


是的,它可以工作,但对我来说,在XML中设置这个并不足够,我需要在设置InserDrawable之后立即在代码中设置它! - Michał Ziobro
2
是的,最近的调用会覆盖之前的设置。因此,如果您在编辑器中设置了填充,然后在代码中设置了背景,那么填充将来自于背景。 - j__m

3
尝试使用带有左内边距的shape代替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>

0

另一个选择:如果你想使用 DP 而不是 PX,请尝试我的建议。根据我的经验,InsetDrawable 只能使用像素,我觉得这很不方便。说实话,我对这个解决方案并不满意,但是嘿,它起作用。

<?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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接