Android在点击时更改背景颜色 [英] Android Change background color when clicked

查看:0
本文介绍了Android在点击时更改背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更改Button的背景颜色当它被单击时,我可以在按下Button时更改背景颜色当我松开Button按钮返回其默认颜色时。我不知道从哪里开始我一直在努力寻找解决这个问题的办法。

`

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.game.dice.MainActivity">

    <Button
        android:id="@+id/but1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 1"
        android:background="@drawable/button_color"
        />
    <Button
        android:id="@+id/but2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 2"
        android:background="@drawable/button_color"/>
</LinearLayout>

`

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
    android:drawable="@color/button_pressed"/>
<item android:state_focused="true"
    android:drawable="@color/button_focused"/> 
<item android:drawable="@color/button_default"/> 
</selector>

推荐答案

这是因为默认情况下,当触摸按钮时,它将接受单击而不是焦点。如果您希望按钮成为焦点并在按下时更改其颜色,请将此代码添加到XML语言中的按钮。

android:focusableInTouchMode="true"

这篇关于Android在点击时更改背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆