XML 中的 Android onClick 与 OnClickListener
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21319996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android onClick in XML vs. OnClickListener
提问by KG6ZVP
I realize that a similarly-worded question has been asked before, but this is different. I am pretty new at developing android apps and I have three questions regarding the difference(s) between the android:onclick=""
XML attribute and the setOnClickListener
method.
我意识到之前有人问过一个类似措辞的问题,但这是不同的。我在开发 android 应用程序方面很新,我对android:onclick=""
XML 属性和setOnClickListener
方法之间的差异有三个问题。
What are the differences between the two? Is the difference between the two implementations found at compile time or run time or both?
What use cases are favorable to which implementation?
What difference(s) does the use of fragments in Android make in implementation choice?
两者之间有什么区别?两种实现之间的区别是在编译时还是运行时或两者兼而有之?
哪些用例有利于哪种实现?
在 Android 中使用片段在实现选择上有什么区别?
回答by Jebasuthan
Difference Between OnClickListener vs OnClick:
OnClickListener 与 OnClick 的区别:
- OnClickListener is the interface you need to implement and can be set to a view in java code.
- OnClickListener is what waits for someone to actually click, onclick determines what happens when someone clicks.
- Lately android added a xml attribute to views called android:onclick, that can be used to handle clicks directly in the view's activity without need to implement any interface.
- You could easily swap one listener implementation with another if you need to.
- An OnClickListener enable you to separate the action/behavior of the click event from the View that triggers the event. While for simple cases this is not such a big deal, for complex event handling, this could mean better readability and maintainability of the code
- Since OnClickListener is an interface, the class that implements it has flexibilities in determining the instance variables and methods that it needs in order to handle the event. Again, this is not a big deal in simple cases, but for complex cases, we don't want to necessary mix up the variables/methods that related to event handling with the code of the View that triggers the event.
- The onClick with function binding in XML Layout is a binding between onClick and the function that it will call. The function have to have one argument (the View) in order for onClick to function.
- OnClickListener 是你需要实现的接口,可以在java代码中设置为一个视图。
- OnClickListener 是等待某人实际点击的东西,onclick 决定当某人点击时会发生什么。
- 最近android给视图增加了一个xml属性,叫做android:onclick,可以用来直接在视图的Activity中处理点击,不需要实现任何接口。
- 如果需要,您可以轻松地将一个侦听器实现与另一个交换。
- OnClickListener 使您能够将点击事件的动作/行为与触发事件的视图分开。虽然对于简单的情况这不是什么大问题,但对于复杂的事件处理,这可能意味着代码的可读性和可维护性更好
- 由于 OnClickListener 是一个接口,实现它的类在确定处理事件所需的实例变量和方法方面具有灵活性。同样,在简单的情况下这不是什么大问题,但是对于复杂的情况,我们不想将与事件处理相关的变量/方法与触发事件的视图的代码混在一起。
- XML 布局中带有函数绑定的 onClick 是 onClick 与其将调用的函数之间的绑定。该函数必须有一个参数(视图)才能使 onClick 起作用。
Both function the same way, just that one gets set through java code and the other through xml code.
两者的功能相同,只是一个通过 java 代码设置,另一个通过 xml 代码设置。
setOnClickListener Code Implementation:
setOnClickListener 代码实现:
Button btn = (Button) findViewById(R.id.mybutton);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myFancyMethod(v);
}
});
// some more code
public void myFancyMethod(View v) {
// does something very interesting
}
XML Implementation:
XML 实现:
<?xml version="1.0" encoding="utf-8"?>
<!-- layout elements -->
<Button android:id="@+id/mybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me!"
android:onClick="myFancyMethod" />
<!-- even more layout elements -->
Performance:
表现:
Both are the same in performance. Xml is pre-parsed into binary code while compiling. so there is no over-head in Xml.
两者在性能上是一样的。xml 在编译时被预先解析为二进制代码。所以在 Xml 中没有开销。
Limitation:
局限性:
android:onClick is for API level 4 onwards, so if you're targeting < 1.6, then you can't use it.
android:onClick 适用于 API 级别 4 以上,因此如果您的目标是 < 1.6,则无法使用它。
回答by Livio
I'm shocked nobody talked about this but be careful, although android:onClick
XML seems to be a convenient way to handle click, the setOnClickListener
implementation do something additional than adding the onClickListener
. Indeed, it put the view property clickable
to true.
我很震惊没有人谈论这个但要小心,虽然android:onClick
XML 似乎是一种处理点击的便捷方式,但setOnClickListener
实现除了添加onClickListener
. 事实上,它把 view 属性设置clickable
为 true。
While it's might not be a problem on most Android implementations, according to the phone constructor, button is always default to clickable = true but other constructors on some phone model might have a default clickable = false on non Button views.
虽然在大多数 Android 实现中这可能不是问题,但根据手机构造函数,按钮始终默认为 clickable = true,但某些手机模型上的其他构造函数在非按钮视图上可能具有默认的 clickable = false。
So setting the XML is not enough, you have to think all the time to add android:clickable="true"
on non button, and if you have a device where the default is clickable = true and you forget even once to put this XML attribute, you won't notice the problem at runtime but will get the feedback on the market when it will be in the hands of your customers !
所以设置 XML 是不够的,你必须一直想着添加android:clickable="true"
非按钮,如果你有一个默认为 clickable = true 的设备,你甚至忘记放置这个 XML 属性,你不会注意到问题在运行时,但会在市场上得到反馈,当它掌握在您的客户手中时!
In addition, we can never be sure about how proguard will obfuscate and rename XML attributes and class method, so not 100% safe that they will never have a bug one day.
此外,我们永远无法确定 proguard 将如何混淆和重命名 XML 属性和类方法,因此并非 100% 安全,以至于有一天它们永远不会出现错误。
So if you never want to have trouble and never think about it, it's better to use setOnClickListener
or libraries like ButterKnife with annotation @OnClick(R.id.button)
所以如果你不想遇到麻烦也从不去想,最好使用setOnClickListener
或者像 ButterKnife 这样的带注解的库@OnClick(R.id.button)
回答by marson
Simply:
简单地:
If you have android:onClick = "someMethod"
in xml, it looks for the public void someMethod
in your Activity class. OnClickListener
is called right from your Activityand it is linked to some particular View
. For example someButton.setOnClickListener
and in the code below is said what has to be done when someButton
is pressed.
如果您有android:onClick = "someMethod"
in xml,它会public void someMethod
在您的 Activity 类中查找。OnClickListener
是从您的 Activity 中直接调用的,它与某些特定的View
. 例如someButton.setOnClickListener
,在下面的代码中说明了someButton
按下时必须执行的操作。
Hope it helps :)
希望能帮助到你 :)
回答by Stephan van Hoof
As said before: they both are a way to add logic in response to an event, in this case a 'click' event.
如前所述:它们都是一种添加逻辑以响应事件的方法,在本例中为“单击”事件。
I would go for a separation between logic and presentation, just like we do in the HTML/JavaScript world: Leave the XML for presentation and add event listeners by means of code.
我会在逻辑和表示之间进行分离,就像我们在 HTML/JavaScript 世界中所做的那样:保留 XML 进行表示并通过代码添加事件侦听器。
回答by Megs
If you have several buttons using only one method, I suggest doing it in java. But if you have a button with one specific method, onClick in XML would be better.
如果你有几个按钮只使用一种方法,我建议用 java 来做。但是如果你有一个带有一种特定方法的按钮,XML 中的 onClick 会更好。
回答by Rohan Vachhani
There are a couple of reasons why you might want to programmatically set an OnClickListener
. The first is if you ever want to change the behaviour of your button while your app is running. You can point your button at another method entirely, or just disable the button by setting an OnClickListener
that doesn't do anything.
您可能希望以编程方式设置OnClickListener
. 第一个是您是否想在应用程序运行时更改按钮的行为。您可以将按钮完全指向另一种方法,或者通过设置OnClickListener
不执行任何操作来禁用按钮。
When you define a listener using the onClick
attribute, the view looks for a method with that name only in its host activity. Programmatically setting an OnClickListener
allows you to control a button's behaviour from somewhere other than its host activity. This will become very relevant when we use Fragments
, which are basically mini activities, allowing you to build reusable collections of views with their own lifecycle, which can then be assembled into activities. Fragments always need to use OnClickListeners
to control their buttons, since they're not Activities, and won't be searched for listeners defined in onClick.
当您使用该onClick
属性定义侦听器时,视图仅在其宿主活动中查找具有该名称的方法。以编程方式设置 anOnClickListener
允许您从其主机活动以外的某个地方控制按钮的行为。当我们使用 时Fragments
,这将变得非常重要,它们基本上是小型活动,允许您构建具有自己生命周期的可重用视图集合,然后可以将其组装到活动中。片段总是需要用来OnClickListeners
控制它们的按钮,因为它们不是活动,并且不会在 onClick 中定义的侦听器进行搜索。
回答by Mustapha Hadid
It's more convenient to always use android:onClick attribute unless you have a good reason not to, for example, if you instantiate the Button at runtime or you need to declare the click behavior in a Fragment subclass.
始终使用 android:onClick 属性会更方便,除非您有充分的理由不这样做,例如,如果您在运行时实例化 Button 或者您需要在 Fragment 子类中声明单击行为。
回答by Seyyed Mahmood Ahmadi
I think main difference between them is:
我认为它们之间的主要区别是:
OnClick: When you click on the button with your finger.
OnClick:当您用手指单击按钮时。
OnClickListner: It is may be a wider choice that be implemented in various codes.
OnClickListner:它可能是在各种代码中实现的更广泛的选择。
For example when you type url "ymail.com", yahoo finds your username and your password from your browser and enable click state button to open your mail. This action should be implemented only in onClickListener.
例如,当您输入 url "ymail.com" 时,雅虎会从您的浏览器中找到您的用户名和密码,并启用单击状态按钮以打开您的邮件。此操作应仅在 onClickListener 中实现。
This is my idea!
这是我的主意!