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

相关推荐
shih94510 小时前
16G 内存不够用之后,我把旧安卓手机接进了 k3s 集群
android·k3s
阿杰m11 小时前
Android源码第三十章:Android Automotive、TV 与桌面模式
android
意念回复20 小时前
Transformer 系列(五):从 Block 到模型——三大架构、因果掩码与自回归生成
android·回归·transformer
松仔log21 小时前
Kotlin中级——KMP
android·开发语言·kotlin
GY-9321 小时前
【Android】SQL数据库
android
GY-931 天前
【Android】适配不同的屏幕尺寸
android
Chenpip11 天前
安卓 14/15 上装不上:四层原因与三行检查
android·app分发·应用分发·海哈游分发·内测
TT哇1 天前
【Android 之旅】Android 通俗易懂记
android·gitee
雨白1 天前
工厂设计模式实战:从简单工厂到抽象工厂的演进之路
android
Digitally1 天前
7 种主流安卓设备备份与恢复方法
android