Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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

like image 402
martin_dk Avatar asked Aug 16 '13 06:08

martin_dk


1 Answers

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.

like image 117
gunar Avatar answered Nov 07 '22 15:11

gunar