Android按键点击事件三种实现方法

1. 在xml文件中为 Button 添加android:onclick属性

由于没有onclick这个函数,onclick下面会提示红色波浪线错误,然后单击一下"onclick"按住键盘上Alt+Enter键,选择在activity中生成函数

复制代码
    public void onclick(View view) {
        Toast.makeText(this,"方法1 点击按键",Toast.LENGTH_SHORT).show();
        //添加你需要代码
    }

2. onClickListener实例

复制代码
    Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(MainActivity.this,"方法2 点击按键",Toast.LENGTH_SHORT).show();
        }
    });

3. 重写onClick方法

复制代码
Button button = (Button) findViewById(R.id.button);
Button button_2 = (Button) findViewById(R.id.button2);
button.setOnClickListener(this);
button_2.setOnClickListener(this);

添加这两行代码时会发现"this"是红色的,需要点击"this"按住键盘上Alt+Enter键第二个指示生成所需要的函数

之后重写onClick函数

复制代码
    if(view.getId() == R.id.button)
        Toast.makeText(this,"方法3 点击按键",Toast.LENGTH_SHORT).show();
    else if (view.getId() == R.id.button2) {
        Toast.makeText(this,"方法3 点击按键222",Toast.LENGTH_SHORT).show();
    }

这边提一句:新版的android好像不能用switch,所以就用了if语句

相关推荐
2501_937193149 小时前
技术加持!PLB-TV:HDR10+UDP 传输
android·源码·源代码管理·机顶盒
霸王大陆11 小时前
《零基础学 PHP:从入门到实战》模块十:从应用到精通——掌握PHP进阶技术与现代化开发实战-2
android·开发语言·php
低调小一15 小时前
在 Android 上获取视频流逐帧时间戳并与 GPS/IMU 对齐(CameraX 实践)
android
Android_Trot15 小时前
Flutter android 多渠道配置,多包名、icon、等配置。
android·flutter
zhangphil17 小时前
Android性能:trace上的锁竞争monitor contention with owner at
android
砖厂小工17 小时前
Now In Android 精讲 9 - Benchmark 与 Baseline Profile
android
愤怒的代码17 小时前
深入解析 SystemUI 依赖注入:Dagger2 与 Hilt 核心机制重温
android·dagger
從南走到北19 小时前
JAVA海外短剧国际版源码支持H5+Android+IOS
android·java·ios
霸王大陆19 小时前
《零基础学 PHP:从入门到实战》模块十:从应用到精通——掌握PHP进阶技术与现代化开发实战-1
android·开发语言·php