一.ToggleButton的使用
ToggleButton(开关按钮)是Android系统中比较简单的一个组件
是一个有选择状态的的按钮,并且需要为不同的状态设置不同的显示文本
首先添加一个线性布局,垂直向下android:orientation="vertical"
添加一个图片ImageView
添加一个ToggleButton,开启的时候显示 android:textOn="开启",关闭的时候,显示android:textOff="关闭"
<?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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:srcCompat="@drawable/turnoff" />
<ToggleButton
android:textOn="开启"
android:textOff="关闭"
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton" />
</LinearLayout>
</LinearLayout>
在后端中
添加一个ToggleButton和ImageView变量
利用id获得XML中的ToggleButton,和ImageView
toggleButton = findViewById(R.id.toggleButton);
imageView = findViewById(R.id.imageView);
当点击toggleButton 的时候调用函数
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
如果isChecked不为空的时候
设置imageView的图片资源为关灯时候的图片,并且有个提示的信息
imageView.setImageResource(R.drawable.turnon);
Toast.makeText(MainActivity.this,"已开启",Toast.LENGTH_SHORT).show();
如果如果isChecked为空的时候,同理也一样
package com.example.test1;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ToggleButton;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity {
ToggleButton toggleButton;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toggleButton = findViewById(R.id.toggleButton);
imageView = findViewById(R.id.imageView);
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
{
imageView.setImageResource(R.drawable.turnon);
Toast.makeText(MainActivity.this,"已开启",Toast.LENGTH_SHORT).show();
}
else{
imageView.setImageResource(R.drawable.turnoff);
Toast.makeText(MainActivity.this,"已经关闭",Toast.LENGTH_SHORT).show();
}
}
});
}
}
二.Switch的使用,用法和ToggleButton的使用类似,
只是android:textOff="关闭" android:textOn="开启"中的文本不会显示出来
<Switch android:textOff="关闭" android:textOn="开启" android:id="@+id/switch1" android:layout_width="300px" android:layout_height="wrap_content" android:text="Switch" />