使用匿名内部类设置CheckBox响应事件

吐司的上下文设置应为activityName.this或别的,this仅代表在当前的内部类
Toast.makeText(MainActivity.this,"CheckBox未选中",Toast.LENGTH_SHORT).show();
 1 CheckBox checkBox=findViewById(R.id.checkB);
 2         checkBox.setChecked(true);
 3         checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
 4             @Override
 5             public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
 6                 if(isChecked){Toast.makeText(MainActivity.this,"CheckBox被选中",Toast.LENGTH_SHORT).show();}
 7                 else {
 8                     Toast.makeText(MainActivity.this,"CheckBox未选中",Toast.LENGTH_SHORT).show();
 9                 }
10             }
11         });

猜你喜欢

转载自www.cnblogs.com/1yats/p/10721647.html