Manu Manjunath
Manu Manjunath

Reputation: 364

Android buttons - difference in listener

I'm new to android development and I see there are 2 different ways to make a button perform a specific task.

The 1st way is to have a setOnClickListener() within your onCreate function.

The 2nd is to create a separate method in its Activity page and call it using the activity's XML using android:onClick="thisFunction"

I have always found it easier to call functions using android:onClick in the XML.

Would this way make the buttons perform slower? When would you experts prefer one way over another?

Upvotes: 1

Views: 67

Answers (1)

Rodrigo Fernandes
Rodrigo Fernandes

Reputation: 177

In my opinion, it's always better to set the onClick in the code, since the xml way only works well with activities. When you try to do that with fragments, it will ask you to choose an activity to handle the onClick() from the xml. Imagine having a single activity app, with lots of fragments, and having all of it's onClick() methods spread across the MainActivity code. It's quite a mess.

Regarding performance setOnClickListener() vs onClick() inside xml, I think it's pretty much the same nowadays.

Upvotes: 1

Related Questions