简体   繁体   English

Android OnClickListener复杂性

[英]Android OnClickListener complexity

I need to know, what is better in terms of complexity. 我需要知道,在复杂性方面哪些更好。 Either to identity a separate onClick method from xml for each button like this: 要么为xml为每个按钮标识一个单独的onClick方法,如下所示:

android:onClick:"clickHandler"

and the java code: 和java代码:

public void clickHandler(View v){ 
         Button b = (Button) v;
         //do something for that button
      };

, or identify one method for all of the buttons, and separate them with if conditions. ,或为所有按钮确定一种方法,并用if条件将它们分开。

Public void clickHandler(View v){
      Button b = (Button) v; 
      if(b.getText().equals("a")){
      }
         elseif(b.getText().equals("b")){
            }
       //And so on.
    }

I am not that good in calculating complexity and so on, but this question just irritates and I can't answer it. 我在计算复杂性方面并不是那么好,等等,但这个问题只是令人恼火,我无法回答。 But what I understand, the first method increases the code lines a lot! 但据我所知,第一种方法增加了很多代码行!

I would use a version of the second option. 我会使用第二个选项的版本。 Create one handler, and then use a switch statement to determine which view received the event. 创建一个处理程序,然后使用switch语句确定哪个视图收到了该事件。 It is code efficient and is not messy at all. 它具有代码效率,并且完全没有杂乱。 Also, you don't need to list that attribute in xml... I personally think it is much easier to findViewById() in your activity and implement onClickListener. 此外,您不需要在xml中列出该属性...我个人认为在您的活动中查找ViewById()并实现onClickListener要容易得多。 Then you can use each button's id in your switch statement. 然后,您可以在switch语句中使用每个按钮的id。

I generally like the latter. 我一般喜欢后者。 Except I tend to do something that looks more like this: 除了我倾向于做一些看起来更像这样的事情:

public void onClick(View v){
   switch(v.getId()){
      case R.id.button_a:
        //do button a logic here
        break;
      case R.id.button_b:
        //do button b logic here
        break;
   }
}

Consider making your Activity implement View.OnClickListener than in your OnCreate() simple attach with findViewById(R.id.button_a).setOnClickListener(this); 考虑使用findViewById(R.id.button_a).setOnClickListener(this);使您的Activity implement View.OnClickListener不是使用OnCreate()简单附加findViewById(R.id.button_a).setOnClickListener(this);

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

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