简体   繁体   English

使用OnClick事件的最佳方法是什么?

[英]What is the best way to use OnClick event?

There are 2 ways to use OnClick event in android studio. 有两种方法可以在android studio中使用OnClick事件。

First method is, 第一种方法是,

Btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    };

Second way is, 第二种方式是,

in MainActivity 在MainActivity中

Btn.setOnClickListener(this);

and Override method onClick 和覆盖方法onClick

@Override
   public void onClick(View v) {
       switch(v.getId()) {
           case R.id.button1:
           // do stuff;
           break;
           case R.id.button2:
           // do stuff;
           break;
       ...
   }

What is the best and most efficient way from above two?? 从两个以上最好和最有效的方法是什么?

Both are good. 两者都很好。 Nothing in wrong on above mentioned methods. 上述方法没有错。 But I would prefer second one with switch statements when I have to listen click events with many views on the other hand If want to listen click event for a view or two I prefer to use first one. 但是当我不得不在另一方面监听具有许多视图的点击事件时,我更倾向于使用switch语句。如果想要监听一两个视图的点击事件,我更喜欢使用第一个。 NOTE: If click events are more than to implement anonymous way (as you implemented in first example) the line of code increases a lot. 注意:如果单击事件不仅仅是实现匿名方式(正如您在第一个示例中实现的那样),则代码行会增加很多。 It looks tedious and to maintain code becomes harder. 它看起来很乏味,并且维护代码变得更难。 But other developer may feel comfortable with this 但其他开发者可能会对此感到满意

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM