BÀI 12 - THAY ĐỔI MÀU BUTTON TRONG LẬP TRÌNH 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):

1 <?xml version="1.0" encoding="utf-8"?>

2 <resources>

3 <color name="red">#f00</color> <!-- Màu đỏ -->

4 <color name="blue">#00f</color> <!-- Màu xanh da trời -->

5 </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>

***Bonus: Nếu bạn muốn tắt dụ auto in hoa text của Button thì bạn nhập lệnh textAllCaps="false" thì android sẽ không auto in hoa text trong Button của bạn nữa và ngược lại.

<?xml version="1.0" encoding="utf-8"?>

<shape

xmlns:android="http://schemas.android.com/apk/res/android"

android:shape="rectangle">


<!-- Set màu nền-->

<solid

android:color="@color/colorPrimaryDark" >

</solid>


<!-- đặt thuộc tính màu và độ rộng của đường viền -->

<stroke

android:width="1dp"

android:color="@color/colorPrimaryDark" >

</stroke>


<!-- các thuộc tính căn chỉnh-->

<padding

android:left="5dp"

android:top="5dp"

android:right="5dp"

android:bottom="5dp" >

</padding>


<!-- và đây là bán kính đường tròn ở 4 góc -->

<corners

android:radius="2dp" >

</corners>


</shape>