Android-ToggleButton和Switch

应用:ToggleButton和Switch在不同状态下,UI也不同

示例如下:

MainActivity.java

package com.example.widgetdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



    }
    public void toggleText(View view){
        TextView tv = findViewById(R.id.textview);
        if (((ToggleButton)view).isChecked()){
            tv.setText("toggle button is on");
        }else {
            tv.setText("toggle button is off");
        }
    }
    public void switchText(View view){
        TextView tv = findViewById(R.id.textview);
        if (((Switch)view).isChecked()){
            tv.setText("toggle button is on");
        }else {
            tv.setText("toggle button is off");
        }
    }
}

activity_main.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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25sp"
        android:text=""

        ></TextView>

    <ToggleButton
        android:id="@+id/togBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOn="@string/textOn"
        android:textOff="@string/textOff"
        android:onClick="toggleText"
        ></ToggleButton>

    <Switch
        android:id="@+id/swiBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOn="@string/textOn"
        android:textOff="@string/textOff"
        android:onClick="switchText"
    />
</LinearLayout>

猜你喜欢

转载自blog.csdn.net/ED_LAI/article/details/132477687