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

相关推荐
hjlgs6 小时前
framework修改快速验证
android
游戏开发爱好者86 小时前
iOS 开发者的安全加固工具,从源码到成品 IPA 的多层防护体系实践
android·安全·ios·小程序·uni-app·cocoa·iphone
安卓理事人6 小时前
安卓内存泄露排查LeakCanary
android
秃了也弱了。8 小时前
MySQL空间函数详解,MySQL记录经纬度并进行计算
android·数据库·mysql
.豆鲨包8 小时前
【Android】Binder机制浅析
android·binder
Nerve10 小时前
GooglePay: API 文档
android·google
Nerve10 小时前
GooglePay: 订阅商品购买流程
android·google
summerkissyou198710 小时前
Audio-触摸音-播放流程
android
Nerve11 小时前
GooglePay: 消耗商品购买流程
android·google
LiteHeaven11 小时前
Android 8.1 Unable to create application data 问题分析
android