在很多app的设置页面,或者是一些功能的开关界面,我们常常用到 Switch(开关) 来展示状态,今天说说新学到的Switch控件。
最基本情况的按钮:
<Switch
android:id="@+id/switch_普通开关"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
这里layout_width:这能设置整个布局的宽度,不能设置具体的Switch的大小,需要使用switchMinWidth属性来设置。
thumb:文字所携带的背景,设置为背景色进行隐藏。不设置会出现一个背景框。
track:设置开关的背景图片,类似于button的background。
textoff、texton:设置开关时的文字显示。
最后说说Switch的点击事件:
private Switch mSwitch;
private TextView mText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSwitch = (Switch) findViewById(R.id.switch_);
mText = (TextView) findViewById(R.id.text_);
// 添加监听
mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
mText.setText("开启");
}else {
mText.setText("关闭");
}
}
});
}