SwitchButton用法
1、Switch是一个可以再两种状态切换的开关控件。用户可以拖动来选择,也可以像选择复选框一样点击切换Switch的状态在布局文件使用方法同TextView:
2、该组件继承自CompoundButton,在代码中可以通过实现CompoundButton.OnCheckedChangeListener接口,并实现其内部类的onCheckedChanged来监听状态变化。
效果图
- 不废话上代码,布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@+id/da"
android:orientation="vertical"
android:layout_height="match_parent">
<Switch
android:id="@+id/switcher"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:textOff="打开片"
android:textOn="关闭片"
android:thumb="@drawable/check" />
</LinearLayout>
- 类文件
import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;
/**
* Created by Administrator on 2016/9/14 0014.
*/
public class SwitchButtonActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.switch_button);
Switch switcher = (Switch)findViewById(R.id.switcher);
switcher.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
Toast.makeText(SwitchButtonActivity.this,"b: "+b,Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(SwitchButtonActivity.this,"b: "+b,Toast.LENGTH_SHORT).show();
}
}
});
}
}
- dome中的位置,记得修改dome清单中的配置,其他类都可以删除,每个类都是一个控件,没有关系
dome下载地址:http://download.csdn.net/download/bobo8945510/9631870