简体   繁体   中英

How do I make the button change color when it's pressed?

I'm a bit new to android programming, so I don't really have an idea of what I'm doing. I want to make a button change color when its pressed. So far, this is what my button looks like:

<Button
    android:id="@+id/c1"
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:background="#FFFFFF" >

</Button>

What do I have to add to it to make it change color when it's pressed?

Define the button selector and set it as background of button

button_selector.xml

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

<item android:state_focused="true" android:drawable="@color/pressed_button_clr"></item>
<item android:state_pressed="true" android:drawable="@color/pressed_button_clr"></item>
<item  android:drawable="@color/default_button_clr"></item>
</selector>

And the xml code is :

<Button
    android:id="@+id/c1"
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:background="@drawable/button_selector" >

</Button>

Because you want to define your own background colours the button would appear as if it's not being clicked, if you remove the background colour you defined it would appear to click. In order to define your own background colours you would have to make a custom button

Creating a custom button

Create shapes matching the colours you would like

Button Clicked shape

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <stroke 
        android:width="1dp" 
        android:color="#505050"/>

    <size android:width="180dp"
        android:height="40dp"/>

    <solid android:color="#505050"/>

</shape>

Button Normal shape

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:width="1dp"/>

    <size android:width="180dp"
     android:height="40dp"/>

     <solid android:color="#4ddedede"/>

</shape>

When you've created these two shapes, create your button to use them

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="false" android:drawable="@drawable/button_normal"/>
    <item android:state_pressed="true" android:drawable="@drawable/button_clicked"/>
</selector>  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM