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

相关推荐
曾经的三心草42 分钟前
Python2-工具安装使用-anaconda-jupyter-PyCharm-Matplotlib
android·java·服务器
Jerry1 小时前
Compose 设置文字样式
android
飞猿_SIR2 小时前
android定制系统完全解除应用安装限制
android
索迪迈科技3 小时前
影视APP源码 SK影视 安卓+苹果双端APP 反编译详细视频教程+源码
android·影视app源码·sk影视
孔丘闻言3 小时前
python调用mysql
android·python·mysql
萧雾宇5 小时前
Android Compose打造仿现实逼真的烟花特效
android·flutter·kotlin
翻滚丷大头鱼5 小时前
android 性能优化—ANR
android·性能优化
翻滚丷大头鱼5 小时前
android 性能优化—内存泄漏,内存溢出OOM
android·性能优化
拜无忧6 小时前
【教程】flutter常用知识点总结-针对小白
android·flutter·android studio
拜无忧7 小时前
【教程】Flutter 高性能项目架构创建指南:从入门到高性能架构
android·flutter·android studio