[Android] Màu của Button Android – Button color Android

Để đặt màu cho Button ta có thể sử dụng android:background=”mã màu” của Button
VD: android:background=”#F00″ => cho ta màu đỏ.
Tuy nhiên với cách này khi click vào Button chúng ta sẽ không nhìn thấy sự phản ứng của Button nên tưởng chừng nó chưa được click.

Để khắc phục điều này ta làm như sau:
Bước 1: Tạo file color.xml trong thư mục res/values với nội dung như sau (file này nhằm định nghĩa các màu cần dùng):

<?xml version="1.0" encoding="utf-8"?>
<resources>
     <color name="red">#f00</color>		<!-- Màu đỏ -->
     <color name="blue">#00f</color>	<!-- Màu xanh da trời -->
</resources>

Bước 2: Tạo file button_color.xml trong thư mục res/drawable (nếu không có thư mục này thì có thể tạo mới ra) với nội dung (file này tạo các màu cho button):

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/red" 	
        android:state_pressed="true"/>		<!-- Hiện màu đỏ khi ấn vào nút -->
    <item android:drawable="@color/blue" 
        android:state_pressed="false"/>		<!-- Hiện màu xanh da trời khi không nhấn nút -->
</selector>

Bước 3: Dùng lệnh android:background=”@drawable/button_color” để đặt màu trong file button_color đã tạo

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:gravity="center">
    <LinearLayout 
        android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:gravity="center">
        <TextView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="30sp"
            android:text="My Button"/>
    </LinearLayout>
    
    <LinearLayout 
        android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:gravity="center"
	    android:layout_marginTop="20dp">

        <Button
            android:id="@+id/ok"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"            
            android:text="Click"
            android:textSize="30sp" 
            android:background="@drawable/button_color"/> <!-- Đặt màu trong file button_color -->

    </LinearLayout>
    
</LinearLayout>

button color Android