是否可以在Android选择器XML代码中使代码更加模块化?

时间:2016-05-11 07:37:01

标签: android xml android-drawable android-selector

我有以下代码

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
            <item android:right="5dp" android:top="5dp">
                <shape>
                    <corners android:radius="@dimen/rounded_corner_standard" />
                    <gradient android:angle="90"
                        android:endColor="#E2E2E2" android:startColor="#BABABA" />
                </shape>
            </item>
            <item android:bottom="2dp" android:left="2dp">
                <shape>
                    <solid android:color="@color/colorPrimaryDark"/>
                    <corners android:radius="@dimen/rounded_corner_standard" />
                </shape>
            </item>
        </layer-list>
    </item>
    <item>
        <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
            <item android:right="5dp" android:top="5dp">
                <shape>
                    <corners android:radius="@dimen/rounded_corner_standard" />
                    <gradient android:angle="90"
                        android:endColor="#E2E2E2" android:startColor="#BABABA" />
                </shape>
            </item>
            <item android:bottom="2dp" android:left="2dp">
                <shape>
                    <solid android:color="@color/colorPrimary"/>
                    <corners android:radius="@dimen/rounded_corner_standard" />
                </shape>
            </item>
        </layer-list>
    </item>
</selector>

从代码中,您会注意到有一些相同的代码,如下所示,只有一个不同的代码使用只有差异

        <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
            <item android:right="5dp" android:top="5dp">
                <shape>
                    <corners android:radius="@dimen/rounded_corner_standard" />
                    <gradient android:angle="90"
                        android:endColor="#E2E2E2" android:startColor="#BABABA" />
                </shape>
            </item>
            <item android:bottom="2dp" android:left="2dp">
                <shape>
                    <solid android:color="@color/*THE ONLY DIFFERENT*"/>
                    <corners android:radius="@dimen/rounded_corner_standard" />
                </shape>
            </item>
        </layer-list>

有没有办法可以将这些代码分组,比如制作模块函数,并传入我的颜色参数......要么使用include还是其他任何方法?如果我想改变一些事情,我不需要改变双方。

0 个答案:

没有答案