按钮上的多个单击侦听器 [英] Multiple click listeners on buttons

查看:67
本文介绍了按钮上的多个单击侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何向XML定义的按钮中添加多个单击事件,就像以前在Java中一样,我们实现了View.onClickListener接口,并通过onClick方法完成了其余工作.
示例:

I want to know how to add multiple click events to buttons defined in XML, as previously, in Java, we implemented View.onClickListener interface and did the rest of the work in onClick method.
Example:

@Override
public void onClick(View v) {

switch (v.getId()) {

    case R.id.oneButton:
        // do your code
        break;

    case R.id.twoButton:
        // do your code
        break;

    case R.id.threeButton:
        // do your code
        break;

    default:
        break;
    }

}

我正在用新的Kotlin制作一个基本的计算器应用程序,但是Kotlin似乎没有这样的规定,相反,我的代码看起来太冗长,因为我将事件分别附加到所有按钮上. 有人可以告诉我在Kotlin如何做同样的事情吗?谢谢

I'm making a basic calculator app with the new Kotlin but it seems Kotlin has no such provisions, instead my code looks too long and verbose, as I'm attaching events to all buttons individually.
Can someone tell me how to do the same way in Kotlin? Thanks

推荐答案

首先在Activity中实现OnClickListener,例如

class MainActivity : Activity , OnClickListener

然后像

func onClick(v:View) {  
   //use when here like
   case R.id.youview -> {
   // do your work on click of view
    }

不要忘记在View上设置clicklistener.

Don't forgot to set clicklistener on your View.

  yourView.setOnClickListener(this)

或者为了更好地理解,请分步进行-

Or for better understanding go step by step -

  1. 在您的Activity中实施OnClickListener.

编译器会要求您实现重写的方法.实施这些.

Compiler will ask you to implement overrided methods. Implement those.

复制粘贴您在onClick方法内编写的Java代码,该代码可以由kotlin本身转换或写下when条件.

Copy paste your java code which you wrote inside onClick method, that can be converted by kotlin itself or write down when conditions.

这篇关于按钮上的多个单击侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆