如何在Android中向渐变<shape>添加填充?

emm*_*mby 51 android

我有一个渐变的形状,我用它作为ListView物品之间的分隔物.我把它定义如下:

<?xml version="1.0" encoding="UTF-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

<gradient
    android:startColor="#ccd0d3"
    android:centerColor="#b6babd"
    android:endColor="#ccd0d3"
    android:height="1px"
    android:angle="0" />

</shape>
Run Code Online (Sandbox Code Playgroud)

我想在渐变的两侧添加6个像素的填充,这样它就不会从屏幕的边缘延伸到边缘.

但是,无论身在何处,我把一个android:left="6px"android:right="6px",它似乎并没有生效.我可以把它放在<shape>元素,<gradient>元素或者单独的<padding>子元素中,<shape>它不会改变任何东西.

如何在列表分隔符的左侧和右侧添加填充?

小智 136

我猜你可以这样组合:

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

    <item android:left="6dp"
          android:right="6dp">

        <shape android:shape="rectangle">
            <gradient android:startColor="#ccd0d3"
                      android:centerColor="#b6babd"
                      android:endColor="#ccd0d3"
                      android:height="1px"
                      android:angle="0"/>
        </shape>
    </item>
</layer-list>
Run Code Online (Sandbox Code Playgroud)

  • 当然不应该使用px - 总是使用**dp**或**sp**. (9认同)
  • @Martin,除非你使用1px的高度作为列表分隔符.请参阅http://stackoverflow.com/questions/3979218/android-listview-divider (3认同)

Way*_*yne 47

使用插图的另一个解决方案

<?xml version="1.0" encoding="UTF-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetLeft="6dp"
    android:insetRight="6dp" >

    <shape   
        android:shape="rectangle">

    <gradient
        android:startColor="#ccd0d3"
        android:centerColor="#b6babd"
        android:endColor="#ccd0d3"
        android:height="1px"
        android:angle="0" />

    </shape>

</inset>
Run Code Online (Sandbox Code Playgroud)


emm*_*mby 22

一个解决方案似乎是用另一个指定适当填充的drawable"包装"我的drawable.

例如,list_divider.xml将是:

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

    <item
        android:left="6dp"
        android:right="6dp"
        android:drawable="@drawable/list_divider_inner" />

</layer-list>
Run Code Online (Sandbox Code Playgroud)

然后list_divider_inner.xml将是原始的drawable:

<?xml version="1.0" encoding="UTF-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

<gradient
    android:startColor="#ccd0d3"
    android:centerColor="#b6babd"
    android:endColor="#ccd0d3"
    android:height="1px"
    android:angle="0" />

</shape>
Run Code Online (Sandbox Code Playgroud)

这导致两个文件指定一个简单的分隔符.我不知道是否有办法只使用一个文件.

  • 这个问题是关于在列表视图项之间使用精细分隔符.对于这种特殊情况,我特别想要使用单个像素分频器,无论设备的分辨率如何,所以px是正确的. (6认同)