bilanush
bilanush

Reputation: 139

What is the difference between writing onClick() in the XML file to writing listener with onClick function in the Java file?

In Android you can write in button for example the onClick() function and linking the function to it. But most of the time I see people not doing it but activating onClickListener in the Java file to the button.
Why? What are the differences between the two? Are there cases when you are not allowed to use one of them?

Upvotes: 0

Views: 56

Answers (2)

Renjith Thankachan
Renjith Thankachan

Reputation: 4346

Short Explanation:

onClick via xml is good for fixed implementation in your code, but using OnClickListener is better for complex app structure with multiple UI elements or complex UI flow, but they both do the exact same thing.

Detailed:

when you set onClick via layout, LayoutInflator initiated by setContentView pass this attribute to respected view constructor & managed by the views code.

But by using OnClickListener you can alter the behaviour of the control of click event management when it comes to complex app structure.

Below is snap of the internal implementation of onClick attribute

case R.styleable.View_onClick:
                    if (context.isRestricted()) {
                        throw new IllegalStateException("The android:onClick attribute cannot "
                                + "be used within a restricted context");
                    }

                    final String handlerName = a.getString(attr);
                    if (handlerName != null) {
                        setOnClickListener(new DeclaredOnClickListener(this, handlerName));
                    }

internal implementation itself uses setOnClickListener, so both are same, as i mentioned above, using xml onClick option is good only when app is simple, otherwise use Listener.

Upvotes: 3

Eddie Curtis
Eddie Curtis

Reputation: 1237

Functionally you are able to use either and they will both do the same thing. There is no restriction on which one you use, however many developers will favor using the Java code because it's a bit more flexible and allows you to add more functionality if you need to. Sometimes you might see people adding a very basic method call in the XML file which then links to a Java method doing everything they need.

All in all it's just a matter of preference and coding style.

Upvotes: 0

Related Questions