在activity_main.xml
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="开灯"
android:textOff="关灯"
android:onClick="click"
/>
MainActivity.java中
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View view){
ToggleButton t = (ToggleButton) view ;
//t.getText()是拿到的是点击后按钮上的文本
if(t.getText().equals("开灯")){
Toast.makeText(this, "灯打开了", 0).show() ;
}else{
Toast.makeText(this, "灯关了", 0).show() ;
}
}
}