csdnuuu 2020-02-03
ToggleButton和Switch
状态开关ToggleButton与开关switch也是由button按钮派生出来的,因此他们的本质也是按钮,button支持的各种属性,方法toggleButton和switch也适用。
ToggleButton常用的属性:
android:textOff:按钮关闭时显示的文本;
android:textOn:按钮开启时显示的文本;
Switch也用于开关按钮。Switch和ToggleButton稍有区别:ToggleButton是按下弹起的开关,而Switch是左右滑动的开关。
开关监听为:setOnCheckedChangeListener,覆写onCheckedChanged(CompoundButton buttonView, boolean isChecked)方法,其中isChecked表示是否选中。
layout文件
<?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_open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="开"
android:textOff="关"
android:checked="true"/>
<Switch
android:id="@+id/sw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tbtn_open"
android:layout_marginTop="20dp"
android:checked="true"/>
</RelativeLayout>Activity
public class ToggleButtonActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener{
private ToggleButton mBtnopen;
private Switch mBtnsw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toggle_button);
mBtnopen = findViewById(R.id.tbtn_open);
mBtnsw = findViewById(R.id.sw);
mBtnopen.setOnCheckedChangeListener(this);
mBtnsw.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
switch (compoundButton.getId()){
case R.id.tbtn_open:
if(compoundButton.isChecked()) Toast.makeText(this,"开",Toast.LENGTH_SHORT).show();
else Toast.makeText(this,"关",Toast.LENGTH_SHORT).show();
break;
case R.id.sw:
if(compoundButton.isChecked()) Toast.makeText(this,"开关:ON",Toast.LENGTH_SHORT).show();
else Toast.makeText(this,"开关:OFF",Toast.LENGTH_SHORT).show();
break;
}
}
}效果图

