Android——复选按钮和开关按钮

时间:2023-03-09 03:45:48
Android——复选按钮和开关按钮

复选按钮和开关按钮代码如下:

  <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="范冰冰"
android:id="@+id/cb_1"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="章子怡"
android:id="@+id/cb_2"
android:checked="true"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="开"
android:textOff="关"
android:id="@+id/tb_1"/>
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开关"
android:id="@+id/sw_1"/>
</LinearLayout>

java类的代码:

 package com.hanqi.testapp2;

 import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Switch;
import android.widget.Toast;
import android.widget.ToggleButton; public class TestActivity1 extends AppCompatActivity { CheckBox cb_1;
CheckBox cb_2;
ToggleButton tb_1;
Switch sw_1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test1);
cb_1 = (CheckBox)findViewById(R.id.cb_1);
cb_2 = (CheckBox)findViewById(R.id.cb_2);
tb_1 = (ToggleButton)findViewById(R.id.tb_1);
sw_1 = (Switch)findViewById(R.id.sw_1); tb_1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Toast.makeText(TestActivity1.this, "ToggleButton开关状态 = "+(isChecked?"开":"关"), Toast.LENGTH_SHORT).show(); //学习java时的小技巧——三元运算符
}
}); sw_1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Toast.makeText(TestActivity1.this, "Switch开关状态 = "+(isChecked?"开":"关"), Toast.LENGTH_SHORT).show();
}
}); //监听器的实例
CB_OnCheckedChangeListener cb1 = new CB_OnCheckedChangeListener();
//监听器的绑定
cb_1.setOnCheckedChangeListener(cb1);
cb_2.setOnCheckedChangeListener(cb1);
//公共的复选按钮的监听器
class CB_OnCheckedChangeListener implements CompoundButton.OnCheckedChangeListener
{
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
CheckBox cb = (CheckBox)buttonView;
String str = cb.getText().toString();
if(isChecked)
{
Toast.makeText(TestActivity1.this, str+"被选中", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(TestActivity1.this, str+"被取消选中", Toast.LENGTH_SHORT).show();
}
}
}
}