最佳实践安卓的onClick XML属性或setOnClickListener? [英] Best practice android:onClick XML attribute or setOnClickListener?

查看:261
本文介绍了最佳实践安卓的onClick XML属性或setOnClickListener?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面谷歌的Andr​​oid教程,并发现有两种方式获取部件回调按标题(或唯一的onClick - 我不知道)。

I'm following Google's Android tutorial and discovered that there are two ways you get widget callbacks as per title (or only onClick - I don't know).

我是一名高级的Java Swing开发人员,所以内部类的方式让我有宾至如归的感觉:)不过,据我所知,XML的方法是较新的 - 因此谷歌必须增加它的一个原因。

I'm a Senior Java Swing Developer so the inner class approach make me feel at home :) But I understand that the xml approach is newer - so google must have added it for a reason.

什么道理吗?它是更好这样做在Android平台上这样一来,如果内部类的办法,现在要避免(在支持它的版本)?

What is the reasoning here? Is it "nicer" to do it this way on the android platform, should the inner class approach now be avoided (on versions that support it)?

推荐答案

我不使用XML 的onClick 属性,因为这意味着活动正在膨胀的XML必须实现的onClick值的方法。但是,如果你做一些重构和更改这个方法,那么你会得到运行时异常,如果所做的更改不相关的XML。或者,如果你想使用一些包括合并

I am not using the XML onClick attribute because that means the Activity that is inflating the XML must implement the onClick value method. But if you do some refactoring and you change this method, then you'll get runtime exceptions if the changes are not correlated to XML. Or if you want to use some include or merge.

要添加更多:如果你使用的碎片,你必须<一个href="http://stackoverflow.com/questions/6091194/how-to-handle-button-clicks-using-the-xml-onclick-within-fragments">delegate click事件该定义的的onClick XML属性的片段。

To add more: if you use fragments you have to delegate the click event to the fragment that defined onClick XML attribute.

这是少code确实,但为了保持/重构例如code它使事情困难的,开放的错误。所以,不要在生产code使用它。

It's less code indeed, but in order to maintain/refactor such code it makes things difficult and open to errors. So don't use it in production code.

这篇关于最佳实践安卓的onClick XML属性或setOnClickListener?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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