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

相关推荐
j***57682 分钟前
MySQL——表操作及查询
android·mysql·adb
轻口味13 分钟前
基于Rokid Glasses的AI助盲应用实践:让科技点亮视障者的世界
android
j***894640 分钟前
MySQL数据的增删改查(一)
android·javascript·mysql
小画家~1 小时前
第三十四:golang 原生 pgsql 对应操作
android·开发语言·golang
r***18641 小时前
FlinkCDC实战:将 MySQL 数据同步至 ES
android·mysql·elasticsearch
p***62991 小时前
mysql-connector-java 和 mysql-connector-j的区别
android·java·mysql
海天鹰1 小时前
ACTION_PICK与ACTION_GET_CONTENT的区别
android
i***68322 小时前
图文详述:MySQL的下载、安装、配置、使用
android·mysql·adb
6***v4172 小时前
MySQL 时区参数 time_zone 详解
android·mysql·adb
王能2 小时前
Android三阶贝塞尔曲线应用——根据指定点画出完美的贝塞尔
android·贝塞尔曲线·图表·顶点