RadioButton Custom ได้แล้วหรอ?


สวัสดีครับ วันนี้เราก็จะมาแนะนำวิธีการเปลี่ยน RadioButton ให้มีรูปแบบตามที่เราต้องการครับ เราก็มาดูวิธีกันเลย
เพิ่มไฟล์ drawable/img_pressed.xml
 <?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid
        android:color="@android:color/transparent"/>
    <size
        android:width="50dp"
        android:height="50dp"/>
</shape>


เพิ่มไฟล์ drawable/img_checked.xml
  <?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid
        android:color="#1BBC9B"/>
    <size
        android:width="50dp"
        android:height="50dp"/>
</shape>

เพิ่มไฟล์ drawable/radio_button_custom.xml
 <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@drawable/img_checked"
        android:state_checked="true"
        android:state_pressed="true"/>
    <item
        android:drawable="@drawable/img_pressed"
        android:state_pressed="true"/>
    <item
        android:drawable="@drawable/img_pressed"
        android:state_checked="true"/>
    <item
        android:drawable="@drawable/img_checked"/>
</selector>

เปิดไฟล์ layout/activity_main.xml สร้าง RadioGroup และ RadioButton
  <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_store"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.todo.geekcreator.todosuccess.MainActivity">
<RadioGroup
    android:id="@+id/radio_group"
    android:gravity="center"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <RadioButton
        android:id="@+id/radio_button_one"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/radio_button_custom"
        android:button="@android:color/transparent"
        android:layout_margin="16dp"
        />
    <RadioButton
        android:id="@+id/radio_button_two"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/radio_button_custom"
        android:button="@android:color/transparent"
        android:layout_margin="16dp"
        />
    
</RadioGroup>
</LinearLayout>

เพียงเท่านี้ก็สามารถเปลี่ยนลักษณะของ RadioButton ได้แล้ว หากมีข้อสงสัยสามารถคอมเมนต์ได้ที่โพสต์ด้านล่างเลยครับ สำหรับวันนี้คงต้องลาไปก่อนสวัสดีครับ

ความคิดเห็น

บทความที่ได้รับความนิยม