Kevin Haube
Kevin Haube

Reputation: 131

Change <Button> color onClick?

<Button
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="Add"
        android:id="@+id/btnAdd"
        android:background="#ff6347"
        android:textColor="#f8f8f8"
        android:layout_marginTop="36dp"
        android:clickable="true"
        android:layout_below="@+id/txtAddress"
        android:layout_centerHorizontal="true"
        android:focusable="true" />

This is my XML Button element and it's fine and dandy...but I want it to be known when it's pressed. How can I go about making it have different styling when pressed vs when not pressed?

Upvotes: 0

Views: 308

Answers (2)

Tamby Kojak
Tamby Kojak

Reputation: 2159

You want to use a selector as the background for the button. Basically you can define the the different shape you want for each state of the button and the shape consists of color, corner radius, and other cool things.

XML file saved at res/drawable/button.xml:

<?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_pressed="true"> <!-- pressed -->
            <shape android:shape="rectangle" >
                <solid android:color="@color/blue" />
            </shape>
        </item>
        <item> <!-- default -->
            <shape android:shape="rectangle" >
                <solid android:color="@color/red" />
            </shape>
        </item>
    </selector>

This layout XML applies the state list drawable to a Button:

<Button
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:background="@drawable/button" />

Upvotes: 0

Raghunandan
Raghunandan

Reputation: 133560

You can use a selector and use a drawables for different states.

http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList

You can also use OnTouchListener and on ACTION_DOWN and ACTION_UP set the color to the buttons

Upvotes: 2

Related Questions