什么是ToggleButton?
ToggleButton一般有两种状态:选中和未选中
并且需要为不同状态设置不同的文本
ToggleButton属性
android:checked=”true”——当前按钮状态,选中为”true”,未选中为”false”
android:textOn=”开”
android:checked=”true”的时候,显示 取决于checked的状态,即当checked=”true”的时候,显示textOn=”开”,当checked=”false”的时候,显示checked=”true”
先来看一下实现效果:
具体代码
android:checked="false"
android:id="@+id/toggleButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textOn="开"
android:textOff="关" />
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/off" />
package com.example.admin.demo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
private ToggleButton tb;
private ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化控件
tb = (ToggleButton) findViewById(R.id.toggleButton);
img = (ImageView) findViewById(R.id.imageView1);
//设置监听器
tb.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
img.setImageResource(isChecked?R.drawable.on:R.drawable.off);
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。