דוגמה למתג וללחצן Android

עכשיו נלמד על ה-Android Toggle Button וה-Switch באפליקציות Android. נדבר ונממש את ה- Switch button Widget ואת ה-ToggleButton widget באפליקציה שלנו.

Android Toggle Button

Android Toggle Button משמש להצגת מצבים on ו-off על כפתור. Switch הוא סוג נוסף של Toggle Button שמשמש בעיקר מאז Android 4.0. Android Switch מספק בקרת מחוון. גם ה-ToggleButton וגם ה-Switch הם מחלקות ירות של מחלקת CompoundButton. מאפייני XML המשמשים להגדרת ToggleButton מתוארים למטה.

  1. android:disabledAlpha: האלפה שיוחלה על המחוון כשהוא מנוטרל
  2. android:textOff: הטקסט לכפתור כשהוא לא מסומן
  3. android:textOn: הטקסט לכפתור כשהוא מסומן

כדי לשנות את ה-ToggleButton תוכל להשתמש בצורה תכנתית בשיטות הבאות.

  1. CharSequence getTextOff(): מחזיר את הטקסט כשהכפתור אינו במצב המסומן
  2. CharSequence getTextOn(): מחזיר את הטקסט כשהכפתור במצב המסומן
  3. void setChecked(boolean checked): משנה את מצב המסומן של הכפתור הזה

מתג Android

מתג Android או ווידג'ט SwitchCompat (חלק מספריית AppCompat המספקת תאימות לאחור עבור גרסאות Android נמוכות יותר עד גרסה Android API v7) הוא מחווד און-אוף מותאם אישית שנראה בדרך כלל בהגדרות הטלפון. יתרונות של ווידג'ט מתג Android:

  1. הוא החלפה הטובה ביותר לתיבות סימון ולכפתורי רדיו
  2. היישום לוקח פחות מדקה
  3. אין צורך להשתמש במשאבים רבים ובתמונות

ה-XML הוא כזה:

<android.support.v7.widget.SwitchCompat
        android:id="@+id/switchButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Switch example"
        />

android:text משמש להצגת טקסט לצד מתג ההחלפה.

דוגמה למתג ולמפסק Android

באפליקציה זו נציג שני ToggleButton ומפסק אחד. מצב ה- Toggle Buttons יוצג ב- SnackBar כאשר ה- FloatingActionButton נלחץ. מצב המפסק משתנה ל- true בכל פעם שכפתור הפעולה של ה- snackbar מוקשה. או המצב יוצג ב- snackbar על ידי החלקת המפסק.

מבנה הפרויקט של מתג ה-Toggle והמתג של Android

קוד מתג ה-Toggle של Android

ה-activity_main.xml נשאר זהה. ה-content_main.xml מכיל שני Toggle Buttons ו-Switch שמסומנים כברירת מחדל בשקר, כפי שמוצג בקטע הקוד שלמטה:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.journaldev.switchandtoggle.MainActivity"
    tools:showIn="@layout/activity_main">

    <ToggleButton
        android:id="@+id/tb1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="ToggleButton 1"
        android:textOff="Off"
        android:textOn="On" />

    <ToggleButton
        android:id="@+id/tb2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/tb1"
        android:layout_alignBottom="@+id/tb1"
        android:layout_toRightOf="@+id/tb1"
        android:text="ToggleButton 2"
        android:textOff="Off"
        android:textOn="On" />

    <android.support.v7.widget.SwitchCompat
        android:id="@+id/switchButton"
        android:layout_width="wrap_content"
        android:layout_centerInParent="true"
        android:checked="false"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Switch example"
        />


</RelativeLayout>

ה-MainActivity.java מוצג למטה:

package com.journaldev.switchandtoggle;

import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {

    ToggleButton tb1, tb2;
    SwitchCompat switchCompat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                StringBuilder result = new StringBuilder();
                result.append("ToggleButton1 : ").append(tb1.getText());
                result.append("\nToggleButton2 : ").append(tb2.getText());

               Snackbar snackbar= Snackbar.make(view, result.toString(), Snackbar.LENGTH_LONG)
                        .setAction("SWITCH ENABLE", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                switchCompat.setChecked(true);
                            }
                        });

                snackbar.setActionTextColor(Color.RED);
                snackbar.show();
            }
        });

        tb1= (ToggleButton)findViewById(R.id.tb1);
        tb2=(ToggleButton)findViewById(R.id.tb2);
        switchCompat=(SwitchCompat)findViewById(R.id.switchButton);

        switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                Snackbar.make(buttonView, "Switch state checked "+isChecked, Snackbar.LENGTH_LONG)
                        .setAction("ACTION",null).show();
            }
        });



    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // להטיף את התפריט; זה מוסיף פריטים לתוך הסרגל הפעולה אם הוא קיים.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // לטפל בלחיצות פריטי תפריט בכאן. הסרגל הפעולה יטפל
        // אוטומטית בלחיצות על הכפתור הבית/למעלה, כל עוד
        // כך שאתה מפרט פעילות אב על פי AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

A String builder is used to get the current state of the toggle buttons and append them to display in the snackbar. Switch button being a subclass of Compound Button, an OnCheckChangeListener is implemented as shown in the code above. The output below is the app in action. This brings an end to android toggle button and switch in android tutorial. You can download the final Android SwitchAndToggle Project from the link below.

הורדת פרויקט ה-Switch וה-Toggle Button של Android

התייחסות: מסמך ה-ToggleButton של Android

Source:
https://www.digitalocean.com/community/tutorials/android-toggle-button-switch-example