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语句

相关推荐
YF021114 分钟前
深度解构Android OkDownload断点续传
android·数据库·okhttp
Co_Hui16 分钟前
Android: Service基本使用
android
恋猫de小郭1 小时前
Android Studio 放着没怎么用,怎么也会越来越卡?
android·前端·flutter
Kapaseker1 小时前
Compose 动画 — 显隐的艺术
android·kotlin
黄林晴1 小时前
Android官方发布 AppFunctions,让系统AI直接调用你的APP
android·agent
2501_915909062 小时前
完整指南:如何将iOS应用上架到App Store
android·ios·小程序·https·uni-app·iphone·webview
赏金术士4 小时前
Retrofit + Kotlin 协程(Android 实战教程)
android·kotlin·retrofit
大炮筒11 小时前
COCOS2DX4.0CPPWIN移植安卓踩坑总结
android
qq_4228286213 小时前
android图形学之SurfaceControl和Surface的关系 五
android·开发语言·python
tongyiixiaohuang14 小时前
轻易云平台助力快麦数据入库MySQL
android·数据库·mysql