1、开关控件ToggleButton、Switch控件简介
该控件起到一个开关的作用,类似于在Android手机中的,打开蓝牙等功能。第一张图是ToggleButton的布局效果,第二张是Switch的布局效果。
2、相关代码
在xml中的布局代码:
<span style="font-size:10px;"><ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:textOn="开"
android:textOff="关"
android:checked="true" />
<Switch
android:id="@+id/open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="蓝牙关闭中"
android:textOn="蓝牙开启中" /></span>
属性介绍:
android:textOff 关闭状态显示的文字,默认值:Off
android:textOn 打开状态显示的文字,默认值:On
android:checked 界面首次展示时,该控件是关闭还是打开的状态,默认值:关闭
单击事件:
CompoundButton.OnCheckedChangeListener
package com.example.togglebtnratingbar;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity implements CompoundButton.OnCheckedChangeListener {
private ToggleButton toggleButton1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toggleButton1 = (ToggleButton) this.findViewById(R.id.toggleButton1);
// 绑定单击事件
toggleButton1.setOnCheckedChangeListener(this);
}
// 处理单击事件
@Override
public void onCheckedChanged(CompoundButton toggleButton, boolean isChecked) {
if (R.id.toggleButton1 == toggleButton.getId()) {
if (isChecked){
Toast.makeText(this, "开", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "关", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}