Thursday, March 12, 2020

Android Switch /SwitchCompat Example

In Android Switch/SwitchCompat , it is used to toggle between two on / off statuses, the option of color size, assigning photos to the Switch.
The switch is a View type, extending from CompoundButton, so it has the same settings, properties, code and XML implementations as TextView, Button, CheckBox so you can refer to those contents first.
Android Switch /SwitchCompat Example

This type of View allows toggling between two states by pressing, or pulling a switch (thumb) sliding on a short track (track). There are two versions of Switch (android.widget.Switch) and SwitchCompat (android.support.v7.widget.SwitchCompat), to ensure modern features are compatible on many devices when using Library Support should use SwitchCompat
Implement XML SwitchCompat
<android.support.v7.widget.SwitchCompat
    android:id="@+id/switch_id"
    android:text="Test Switch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
For example Switch / SwitchCompat
layout/layout_mainactivity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:padding="40dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.SwitchCompat
        android:id="@+id/switch_id"
        android:text="Test Switch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/textview_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
    TextView textView;
    SwitchCompat switchCompat;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_mainactivity);
        textView = findViewById(R.id.textview_id);
        switchCompat = findViewById(R.id.switch_id);
        switchCompat.setOnCheckedChangeListener(
            new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton,
                boolean b) {
                    textView.setText("Switch is " +
                        (switchCompat.isChecked() ? "On" : "Off"));
            }
        });
    }
}

No comments:

Post a Comment