BÀI 42 - THAY ĐỔI TRẠNG THÁI NÚT (StateListDrawable) TRONG LẬP TRÌNH ANDROID
Tài nguyên StateListDrawable <selector>
StateListDrawable là loại Drawable mà nó chứa nhiều phần tử <item> bên trong, mỗi phần tử này biểu diễn một Drawable, chúng biểu diện một vài trạng thái nào đó của View khi làm đối tượng đồ họa cụ thể trong từng loại View như làm nền, làm biểu tượng lựa chọn ...
android:state_pressed="true" Drawable biểu thị trạng thái bị nhấn
android:state_pressed="false" Drawable biểu thị trạng thái không bị nhấn
android:state_checked
android:state_selected
android:state_activated
android:state_focused
android:state_active
android:state_enabled
Tạo file xml có tên res/drawable/statelistexample.xml
<selector
xmlns:android="http://schemas.android.com/apk/res/android"
android:dither="true">
<item android:state_pressed="true">
<shape android:shape="oval">
<gradient android:angle="270"
android:endColor="#D1362B"
android:startColor="#94231B" />
<stroke
android:width="1dp"
android:color="#96231D" />
<corners android:radius="4dp" />
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp" />
</shape>
</item>
<item>
<shape>
<gradient
android:angle="270"
android:endColor="#94231B"
android:startColor="#D1362B" />
<stroke
android:width="1dp" a
ndroid:color="#96231D" />
<corners android:radius="4dp" />
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp" />
</shape>
</item>
</selector>
StateListDrawable này biểu thị hai trạng thái nhấn / không nhấn. Khi không nhấn dùng Drawable có hình chữ nhật, khi nhấn dùng Drawable có hình Oval. Đặt làm nền cho Button có kết quả như sau: