onCheckedChanged的入口参数buttonView

本文探讨了Android中Switch控件的工作原理及其使用方法。重点解析了OnCheckedChangeListener接口的应用场景及其实现方式,通过实例展示了如何利用该接口响应Switch状态变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

刚开始学android的菜鸟一枚,在学Switch的时候遇到一个问题,还请高手指教!
——说,Switch的点击相应用到了OnCheckedChangeListener接口,需要实现onCheckedChanged方法;
该方法原型如下:
        void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 

        很好奇这里的入口参数buttonView和我之前生命的Switch(名称为actionBarSwitch,抄的)变量,这两者是个什么关系。于是我用了“==”比较了两者,结果是相同的!

        那我就不明白了,这里为什么要传入一个已经存在的变量呢?直接用自己生命的Switch类对象actionBarSwitch不行么?有没有了解的点拨下?不胜感激!
package com.example.myapplication; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.Checkable; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.RadioButton; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1 = (Button)findViewById(R.id.b1); t1 = (TextView)findViewById(R.id.t1); t2 = (TextView)findViewById(R.id.t2); t3 = (TextView)findViewById(R.id.t3); t4 = (TextView)findViewById(R.id.t4); c1 = (CheckBox)findViewById(R.id.c1); c2 = (CheckBox)findViewById(R.id.c2); r1 = (RadioButton)findViewById(R.id.r1); r2 = (RadioButton)findViewById(R.id.r2); c1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { t2.setText("C1 已被选中"); } else { t2.setText("C1 未被选中"); } } }); c2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { t3.setText("C2 已被选中"); } else { t3.setText("C2 未被选中"); } } }); r1.setOnCheckedChangeListener((group, checkedId) -> { switch (checkedId) { case R.id.r1: t4.setText("You selected Option 1"); break; 修改
04-03
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值