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

相关推荐
梨落秋霜12 分钟前
Python入门篇【元组】
android·数据库·python
zh_xuan13 分钟前
kotlin定义函数和变量
android·开发语言·kotlin
Digitally2 小时前
Android 上的联系人备份和恢复:5 种可靠且方便的方法
android
默|笙3 小时前
【Linux】进程控制(3)进程程序替换
android·linux·运维
国家二级编程爱好者3 小时前
Android Lottie使用,如何自定义LottieView?
android·前端
bst@微胖子3 小时前
CrewAI+FastAPI实现营销战略协助智能体项目
android·数据库·fastapi
子林Android3 小时前
AndroidStudio修改.android、.gradle、.AndroidStudio路径,释放C盘空间
android·android studio
叶羽西4 小时前
如何对自己开发的系统级APK进行签名
android
lxysbly5 小时前
安卓PCE模拟器下载指南:用手机玩 PC-Engine / TurboGrafx 经典
android·智能手机
Digitally7 小时前
哪款应用最适合将数据从安卓手机传输到 iPhone?
android·智能手机·iphone