openplanning

Hướng dẫn và ví dụ Android Switch

Xem thêm các chuyên mục:

Nhóm phát triển của chúng tôi vừa ra mắt website langlearning.net học tiếng Anh, Nga, Đức, Pháp, Việt, Trung, Hàn, Nhật, ... miễn phí cho tất cả mọi người.
Là một website được viết trên công nghệ web Flutter vì vậy hỗ trợ rất tốt cho người học, kể cả những người học khó tính nhất.
Hiện tại website đang tiếp tục được cập nhập nội dung cho phong phú và đầy đủ hơn. Mong các bạn nghé thăm và ủng hộ website mới của chúng tôi.
Hãy theo dõi chúng tôi trên Fanpage để nhận được thông báo mỗi khi có bài viết mới. Facebook

1- Android Switch

Trong Android. Switch là một điều khiển giao diện người dùng (user interface control) với 2 trạng thái ON/OFF, nó có tính năng gần giống như CheckBox, ToggleButton, nhưng khác về mặt giao diện.
 
Switch khá giống với CheckBox, ToggleButton về tính năng và cách sử dụng. Cả 3 lớp này đều là lớp con của CompoundButton, sự khác biệt nằm ở giao diện của chúng.
Image (Icon)
Switch là một lớp con của Button, vì vậy nó cho phép bạn hiển thị tối đa 4 Icon ở gần 4 cạnh bằng cách sử dụng các thuộc tính android:drawableLeft, android:drawableTop, android:drawableRight, android:drawableBottom, android:drawableStart, android:drawableEnd.

<Switch
    android:id="@+id/switch13"
    android:drawableLeft="@drawable/icon_bus"
    android:drawableTop="@drawable/icon_car"
    android:drawableBottom="@drawable/icon_boat"
    android:text="Switch"
    ... />
android:gravity
Thuộc tính android:gravity được sử dụng để sét đặt vị trí hiển thị văn bản của một Switch. Giá trị của nó là kết hợp của các giá trị sau:
Constant in Java Value Description
Gravity.LEFT left  
Gravity.CENTER_HORIZONTAL center_horizontal  
Gravity.RIGHT right  
Gravity.CLIP_HORIZONTAL clip_horizontal  
Gravity.FILL_HORIZONTAL fill_horizontal  
     
Gravity.TOP top  
Gravity.CENTER_VERTICAL center_vertical  
Gravity.BOTTOM bottom  
Gravity.CLIP_VERTICAL clip_vertical  
Gravity.FILL_VERTICAL fill_vertical  
     
Gravity.START start  
Gravity.END end  
Gravity.CENTER center  
Gravity.FILL fill  

<Switch
    android:id="@+id/switch13"
    android:text="Switch"
    android:gravity="bottom|center"
    ... />
android:switchPadding
Thuộc tính android:switchPaddiing cho phép bạn sét đặt 1 khoảng cách giữa tracktext của Switch.

<Switch
    android:id="@+id/switch1"
    android:drawableLeft="@drawable/icon_alarm"
    android:switchPadding="10dp"
    android:text="Alarm"
    ... />
android:layoutDirection = "rtl"
Thuộc tính android:layoutDirection được hỗ trợ từ Android 4.2 (API Level 17), nó cho phép bạn thiết lập chiều bố trí (Layout direction) của một View. Theo mặc định thuộc tính này có giá trị "ltr" (Left to Right).
Để có thể sử dụng thuộc tính android:layoutDirection, bạn cần mở tập tin build.gradle (Module: app) và sửa đổi giá trị của minSdkVersion, và đảm bảo rằng giá trị mới lớn hơn hoặc bằng 17.

<!-- Layout Direction Default: Left to Right -->
<Switch
    android:id="@+id/switch41"
    android:switchPadding="5dp"
    android:text="Alarm"
    ... />

<!-- Layout Direction: Right to Left -->
<Switch
    android:id="@+id/switch42"
    android:layoutDirection="rtl"
    android:switchPadding="5dp"
    android:text="Alarm"
    ... />
textOn/textOff
Android 5.0 (API Level 21) cho phép bạn hiển thị textOn/textOff tương ứng với các trạng thái ON/OFF của Switch.

<!-- textOn/textOff = ON/OFF (Default) -->
<Switch
    android:id="@+id/switch51"
    android:text="Alarm"

    android:showText="true"
    ... />


<!-- textOn/textOff = Enabled/Disabled -->    
<Switch
    android:id="@+id/switch52"  
    android:text="Alarm"

    android:showText="true"
    android:textOff="Disabled"
    android:textOn="Enabled"
    ... />
toggle()
Cả 4 lớp ToggleButton, CheckBox, RadioButton, Switch đều là lớp con của CompoundButton vì vậy chúng được thừa kế phương thức toggle(), Đây là phương thức thường được sử dụng để chuyển đổi trạng thái của chúng từ ON (Checked) sang OFF (Unchecked), và ngược lại.

CompoundButton button = (Switch) findViewById(R.id.switch);

button.toggle();

2- Switch Styles

Thuộc tính style là một tùy chọn của Switch, nó cho phép bạn sét đặt kiểu dáng cho Switch. Có một vài kiểu dáng sẵn có trong thư viện của Android mà bạn có thể sẵn sàng sử dụng.
Chú ý: Hiện tại, số lượng style sẵn có trong thư viện không nhiều, và không thực sự khác biệt so với kiểu dáng mặc định. Điều này thật đáng thất vọng.
Switch Styles Example

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView61"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:text="TextAppearance.AppCompat.Widget.Switch"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Switch
        android:id="@+id/switch61"
        style="@style/TextAppearance.AppCompat.Widget.Switch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:showText="false"
        android:text="Alarm"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView61" />

    <TextView
        android:id="@+id/textView62"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:text="Widget.AppCompat.CompoundButton.Switch"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/switch61" />

    <Switch
        android:id="@+id/switch62"
        style="@style/Widget.AppCompat.CompoundButton.Switch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:showText="false"
        android:text="Alarm"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView62" />

    <TextView
        android:id="@+id/textView63"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:text="Widget.Material.CompoundButton.Switch"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/switch62" />

    <Switch
        android:id="@+id/switch63"
        style="@android:style/Widget.Material.CompoundButton.Switch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:showText="false"
        android:text="Alarm"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView63" />

    <TextView
        android:id="@+id/textView64"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:text="Widget.Material.Light.CompoundButton.Switch"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/switch63" />

    <Switch
        android:id="@+id/switch64"
        style="@android:style/Widget.Material.Light.CompoundButton.Switch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:showText="false"
        android:text="Alarm"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView64" />

</androidx.constraintlayout.widget.ConstraintLayout>

3- Switch Events

Có khá nhiều các sự kiện liên quan tới một Switch, nhưng 2 sự kiện sau được sử dụng thường xuyên nhất:
  • setOnClickListener(View.OnClickListener)
  • setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener)
On Click Event:
Sự kiện xẩy ra khi người dùng nhấp (click) vào Switch, cũng giống như hành động của người dùng khi nhấp vào một Button.

Switch switch1 = (Switch) findViewById(R.id.switch1);

switch1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        boolean checked = ((Switch) v).isChecked();
        if (checked){
            // Your code  
        }
        else{
            // Your code
        }
    }
});
On Checked Change Event:
Sự kiện xẩy ra khi Switch thay đổi trạng thái, do hành động của người dùng hoặc do tác dụng của việc gọi phương thức setChecked(newState), ..

Switch switch1 = (ToggleButton) findViewById(R.id.switch1);

switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if(isChecked)  {
           // Your code
        } else {
           // Your code
        }
    }
});

Xem thêm các chuyên mục: