ToggleButton:有两种状态,选中和未选中状态,并且需要为不同的状态设置不同的显示文本。
属性:android:checked="true" //为true时显示textOn的文本内容,false时显示为textOn的文本内容。
android:textOff="关"
android:textOn="开"
一个开关灯泡代码的实现:
MainActivity.java
package com.example.xuhai.test;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
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.test);
tb=(ToggleButton)findViewById(R.id.tg1);
img=(ImageView)findViewById(R.id.img1);
tb.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//buttonView----代表被点击控件的本身
//isChecked----代表被点击控件的状态
img.setBackgroundResource(isChecked?R.drawable.on:R.drawable.off);
}
}
test.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="@+id/textView" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="小测试"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="开关灯泡"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
>
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tg1"
android:textOn="开"
android:textOff="关"
/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/off"
android:id="@+id/img1"
/>
</LinearLayout>
</LinearLayout>
显示结果:
总结:继承OnCheckedChangeListener接口,实现onCheckedChangedd方法,调用三目运算符来实现灯泡的开关状态。