Button 点击后改变颜色 (不是点击后改变颜色又恢复)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/p4885056000/article/details/53086972

惯例先上效果图

效果

1.首先我们想制作这个按钮的样式

创建一个selector的xml文件规定了,按钮,被按下和不被按下时的背景颜色不懂的同学点击这里

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Non focused states -->
    <item android:state_focused="false" android:state_selected="false" android:state_pressed="false" android:drawable="@color/white" />
    <item android:state_focused="false" android:state_selected="true" android:state_pressed="false" android:drawable="@color/yellow" />
    <!-- Focused states -->
    <item android:state_focused="true" android:state_selected="false" android:state_pressed="false" android:drawable="@color/yellow" />
    <item android:state_focused="true" android:state_selected="true" android:state_pressed="false" android:drawable="@color/yellow" />

    <!-- Pressed -->
    <item android:state_selected="true" android:state_pressed="true" android:drawable="@color/yellow" />
    <item android:state_pressed="true" android:drawable="@color/yellow" />

</selector>

2.在button布局文件里设置背景色为selector的样式

    android:background="@drawable/selector_icon_list"

3.我们在onClick方法里添加获取焦点的代码(那三行)

btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    v.setFocusable(true);
                    v.requestFocus();
                    v.requestFocusFromTouch();
                    // btn.setFocusable(true);
                    //btn.setFocusableInTouchMode(true);
                    //btn.requestFocus();
                    //btn.requestFocusFromTouch();

                }
            });

然后就实现了

展开阅读全文

没有更多推荐了,返回首页