Dùng State List để tạo các style thay đổi theo trạng thái (focus, click…)
Khi có yêu cầu tạo ra các đối tượng sẽ sử dụng các style khác nhau tùy theo trạng thái. Ví dụ như một nút nhấn khi bình thường thì xài một hình, khi focus thì một hình, khi click thì một hình… ta sử dụng State List để có thể làm được việc này. Chi tiết từng trạng thái với ý nghĩa gì và xài tham số nào tham khảo trang trên để biết cách sử dụng. Dưới đây sẽ ghi lại quá trình thực hiện với dự án của mình, tạo ra nút nhấn có 2 trạng thái như sau:
Dưới đây là các bước thực hiện:
- Tạo ra một file xml trong thư mục res/drawable, ở đây sẽ đặt tên là button_nearby_atm.xml, như vậy thì khi sử dụng mình sẽ dùng là @drawable/button_nearby_atm. Nội dung của file này theo như quy định của android như sau:
<?xml version="1.0" encoding="utf-8"?>
Có thể thấy ý nghĩa của từng item trong file xml như phần chú thích. Tra cứu thêm ở trang hướng dẫn của Android bằng link ở trên.
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:state_enabled="true"
android:drawable="@drawable/button_nearby_atm_active" /> <!-- Clicked -->
<item
android:state_focused="true"
android:state_enabled="true"
android:drawable="@drawable/button_nearby_atm_active" /> <!-- Focused -->
<item
android:state_enabled="true"
android:drawable="@drawable/button_nearby_atm_inactive" /> <!-- Default -->
</selector> - Tiếp theo tạo một style (Có thể sử dụng trực tiếp trong file giao diện main.xml nhưng ở đây tách ra các định nghĩa thành một file style riêng để tiện việc quản lý và thay đổi nếu muốn sau này). Tạo file iATM_button.xml trong thư mục res/values có nội dung như sau:
<?xml version="1.0" encoding="utf-8"?>
Ở đây ta đã tạo ra một style sử dụng State List mà ta vừa định nghĩa ở trên có tên là iButton.ButtonNearATM (Để ý thấy giá trị android:background mà ta dùng chính là chỉ tới file xml vừa tạo ra ở bước 1)
<resources>
<style name="iButton" parent="@android:style/Widget.Button">
<item name="android:layout_centerHorizontal">true</item>
<item name="android:layout_marginTop">20dip</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_width">wrap_content</item>
</style>
<style name="iButton.ButtonNearATM" parent="@style/iButton">
<item name="android:background">@drawable/button_nearby_atm</item>
</style>
</resources> - Cuối cùng là tạo một Button sử dụng style mà ta vừa định nghĩa. Mở file res/layout/main.xml lên thêm vào dòng sau:
<Button
android:id="@+id/ButtonNearATM"
style="@style/iButton.ButtonNearATM" />
Kết quả là ta có được như trên hình ở phía trên. Hi vọng là giúp ích được cho ai gặp phải yêu cầu như trên mà chưa tìm ra cách thực hiện.


