ToggleButton 继承于android.widget.CompoundButton,意思是可切换的,这就说明其有不同状态,选中和没有选中,这里用ToggleButton 实现一个小例子熟悉一下ToggleButton 。
最终效果:
先说一下ToggleButton 的几个基本属性:
android:textOn="yes" //打开时的文本
android:textOff="no" //关闭时的文本
android:checked="false" //是否选中
android:autoText="true" //text是自动可编辑的
android:disabledAlpha="1"//设置按钮在禁用时透明度
android:background="@drawable/togglebtn_check" //背景
两张背景图:
主要使用:
private ToggleButton tBtn = null;
private ImageView lamp1,lamp2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main_activity2);
tBtn = (ToggleButton) findViewById(R.id.toggleBtn);
lamp1=(ImageView) findViewById(R.id.lamp1);
lamp2=(ImageView) findViewById(R.id.lamp2);
tBtn.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
String result = "关闭";
if (isChecked) {
result = "打开";
lamp1.setVisibility(View.GONE);
lamp2.setVisibility(View.VISIBLE);
} else {
result = "关闭";
lamp1.setVisibility(View.VISIBLE);
lamp2.setVisibility(View.GONE);
}
Toast.makeText(getApplicationContext(), result, 1).show();
Log.i("yqy", "是否选中@@@@" + isChecked + tBtn.getText());
}
});
}
togglebtn_check.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/btn_on"></item>
<item android:state_checked="false" android:drawable="@drawable/btn_off"></item>
</selector>