在搬运点击方式的差异 [英] A difference in to ways of handling clicks

查看:155
本文介绍了在搬运点击方式的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个总的初学者编码为Android和在一般和各种教程到目前为止的Java,我发现处理按钮单击两种方式。

第一个:

  button.setOnClickListener(新OnClickListener(){
            公共无效的onClick(视图v){
                //做你的事
            }
        });

第二个涉及到把安卓的onClick =的someMethod在按钮的属性在main.xml中,然后只需创建方法的someMethod 中的活动。

我想知道是在这两种方法的区别。一个比另一个更好呢?或做他们的工作只是巧妙不同?对我来说,他们似乎做同样的:P

感谢!


解决方案

  

我想知道是在这两种方法的区别。一个
  比另一种更好?


的结果是一样的。但不同的是在code的可读性。

 安卓的onClick =的someMethod

这种方法我不推荐给你。
搜索结果
我向你推荐使用匿名类像你上面的意思。
搜索结果还您类可以实现例如 View.OnClickListener 然后你只需要执行的onClick()方法,你可以有许多小部件的一种方法。

 公共类主要活动扩展实现View.OnClickListener {
   公共无效的onClick(查看视图){
      开关(view.getId()){
         案例R.id.startBtn:
            // 做一些工作
         打破;
         案例R.id.anotherWidgetId:
            // 做一些工作
         打破;
      }
   }
}

我觉得这也是很好的做法,只有一个方法和code有较少的线条和更干净。

I'm a total beginner in coding for Android and java in general and so far in various tutorials I found two ways of handling buttons being clicked.

The first one:

button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                //do your thing
            }
        });

The second one involves putting android:onClick="someMethod" in a button's properties in the main.xml and then simply creating the method someMethod in the activity.

I was wondering what is the difference in those two approaches. Is one better than another? Or do they work only subtly differently? To me they seem to do the same :P

Thank!

解决方案

I was wondering what is the difference in those two approaches. Is one better than another?

The result is same. But difference is in readability of code.

android:onClick="someMethod"

this approach i don't recommend to you.

I recommend to you use anonymous classes like you meant above.

Also your class can implement for example View.OnClickListener and then you only have to implement onClick() method and you can have one method for many widgets.

public class Main extends Activity implements View.OnClickListener {
   public void onClick(View view) {
      switch(view.getId()) {
         case R.id.startBtn:
            // do some work
         break;
         case R.id.anotherWidgetId:
            // do some work
         break;
      }
   }
}

I think this is also good practice, you have only one method and code have less lines and is cleaner.

这篇关于在搬运点击方式的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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