0
votes

Events in Android require a listener and a handler. This is evident where we see in a Java class that there is an Onclicklistener and an Onclick method within that listener.

I'm confused with the XML Onclick method however, because it doesn't have an Onclicklistener. Are they always neccesary, or is the listener hidden in this case?

<Button
  android:Onclick="myMethod"
/>

public void myMethod(View view)
{
  //do magic here 
}
2

2 Answers

1
votes

Basically when the attributes (like layout_width, onClick and so on) are parsed during creation of the View, an onClickListener is created for this View if this attribute has been set in XML. You can look this up for example here since it's open source.

Keep in mind that I was looking at the View class since Button extends TextView and TextView extends View.

To explain it a bit further: When you create a View via XML, all the attributes will be parsed. Then the properties of the View are set according to those attributes. You can also do this yourself when defining a custom View.

Answering your question simply: Yes an onClickListener is created "hidden" behind the XML during View creation

0
votes

There is no difference between setting OnClickListener in Java code or in XML. If you want to set the listener via the XML you have to implement the corresponding method in Java code. When you're setting the listener via XML, then in parsed in View constructor and sets the listener for you automatically:

case R.styleable.View_onClick:
        ...
    final String handlerName = a.getString(attr);
        if (handlerName != null) {
            setOnClickListener(new DeclaredOnClickListener(this, handlerName));
        }
    break;

It will look like this. XML code:

<Button android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Text"
    android:onClick="onClickFromXml" />

Then in Java code:

public void onClickFromXml(View v) {
    // your click listener implementation
}