Best practice android:onClick XML attribute or setOnClickListener?-ThrowExceptions

Exception or error:

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

How to solve:

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.

###

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.

###

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.

###

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *