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

标签 android button themes 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>

最佳答案

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

button_selector.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>

button_default.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>

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

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

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

关于android - 如何为按钮选择器设置不同的主题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36387423/

相关文章:

android - 在自定义 View onDraw 中使用硬件层

android - 如何重构一个包含很多监听器内部类的类?

java - 从 Github 克隆项目后将图标设置到 jButton 时出现 Null 异常错误

android - 在屏幕上随机移动按钮而不点击

android - 将 Theme.Dialog 更改为 Android 中的 Theme.Light.Dialog

java - 调用两次dispatchKeyEvent()

java - Android 物理/电容式导航按钮

WPF:找不到 Microsoft_Windows_Themes

android - 自定义 ListView 项目中的 View 没有应用主题

android - SYSTEM_UI_FLAG_LIGHT_STATUS_BAR 和 FLAG_TRANSLUCENT_STATUS 已弃用