Best practice android:onClick XML attribute or setOnClickListener? [duplicate]

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

This question already has an answer here:

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).

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.

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)?

回答1:

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.

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

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.



回答2:

You can define widgets like button both by xml and programatically. Can has given a capabity to add the listener both ways. So there is no advantage of one over another.

If you want to do layout specific work from xml, the android has given you a capability to do that.

But someone may define layout progmatically and then will have to define click listener from code.

But there are people who use a mix of it.

I hope you understand what I mean.

If you do it programatically, you can just write onClick() and iside that write a switch case and based on view ids you can define the behaviour which i personally feel is easier to work with.



回答3:

If the buttons are going to be there always and same action is going to be executed always, then using declarative event handlers makes sense. Like when you don't even need to do a findViewById() for that button.

If you may want to enable/disable clicking or may be generating buttons dynamically etc etc, then setting up event handlers dynamically in code makes sense.



回答4:

View.OnClickListener is an interface, which defines the onClick(View) method.

You will implement both the interface and the method in your code.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!