如何为按钮选择器设置不同的主题?

Suj*_*ana 5 android themes button selector

如何根据当前应用程序主题为按钮选择器设置不同的样式?

这是我的button_selector.xml

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

    <item android:state_pressed="true">
        <color android:color="@color/color_theme1"/>
        </item>
 <!-- pressed -->
    <item android:drawable="@color/transparent"/>
 <!-- default -->

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

Hou*_*ass 3

由于您的应用程序主题颜色位于 color.xml 中的 color_primary 中。您可以像这样在选择器中使用它。但是您必须创建两个可绘制文件,一个用于默认状态,另一个用于 selected_state。

按钮选择器.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!--selected/pressed/focused -->
<item       android:state_selected="true"
            android:drawable="@drawable/button_selected"
            />
    <item android:drawable="@drawable/button_default"/>
 <!-- default -->

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

按钮_默认.xml:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<!--this is to give gradient effect -->
<gradient   android:angle="270"
               android:startColor="@color/gray"
               android:endColor="#@color/gray"
               />
<!-- this will make corners of button rounded -->
<corners    android:topLeftRadius="5dip"
               android:bottomRightRadius="5dip"
               android:topRightRadius="5dip"
               android:bottomLeftRadius="5dip"/>

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

按钮_selected.xml:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<!--this is to give gradient effect -->
<gradient   android:angle="270"
            android:startColor="@color/color_primary"
            android:endColor="#@color/color_primary"
            />
<!-- this wil make corners of button rounded -->
<corners    android:topLeftRadius="5dip"
               android:bottomRightRadius="5dip"
               android:topRightRadius="5dip"
               android:bottomLeftRadius="5dip"/>

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

您还必须以编程方式执行以下操作,以便该按钮保持选中状态。

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(v.isSelected())
                {
                    v.setSelected(false);
                }
                else
                {
                     v.setSelected(true);
                }
            }
        });
Run Code Online (Sandbox Code Playgroud)