Android 学习:
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Switch;
import android.widget.ToggleButton;
public class ToggleButtonDemo extends Activity {
/*
* ToggleButton和Switch
* 作用:带有切换效果的按钮(开关按钮)
* 区别在于:Switch会比ToggleButton多一个滑动效果
*
* 监控按钮的状态的切换
* */
ToggleButton tbtn;
Switch s;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.togglebtn);
tbtn = (ToggleButton)findViewById(R.id.tbtn);
s = (Switch)findViewById(R.id.switch1);
tbtn.setOnCheckedChangeListener(new OnCheckedChangeListener() {
/*
* 参数一代表选择的togglebutton对象,
* 参数二代表当前按钮的选择状态,true--on状态,false--off状态
* */
@Override
public void
onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
Log.i("ToggleButton", "ToggleButton checked changed:状态="+isChecked);
}
});
s.setOnCheckedChangeListener(new OnCheckedChangeListener() {
/*
* 参数一代表选择的Switch对象,
* 参数二代表当前按钮的选择状态,true--on状态,false--off状态
* */
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
Log.i("Switch", "Switch checked changed:状态="+isChecked);
}
});
}
}
R.layout.togglebtn
togglebtn.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=" http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ToggleButton android:id="@+id/tbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="30dp"
android:textOn="打开"
android:textOff="关闭"
android:text="ToggleButton当前状态是:"
/>
<Switch android:id="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_below="@+id/tbtn"
android:text="Switch当前状态是:"
/>
</RelativeLayout>
<RelativeLayout xmlns:android=" http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ToggleButton android:id="@+id/tbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="30dp"
android:textOn="打开"
android:textOff="关闭"
android:text="ToggleButton当前状态是:"
/>
<Switch android:id="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_below="@+id/tbtn"
android:text="Switch当前状态是:"
/>
</RelativeLayout>