1

If I want something to happen when a button is clicked what is the difference between the two methods? The first seems much simpler.

In layout

<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage" />

In activity

public void sendMessage(View v) {
 // do whatever
}

OR

private OnClickListener listener = new OnClickListener() {
   public void onClick(View v) {
     // do whatever
   }
};

protected void onCreate(Bundle savedValues) {
    // Capture our button from layout
    Button button = (Button)findViewById(R.id.mybutton);
    // Register the onClick listener with the implementation above
    button.setOnClickListener(listener);
}
  • Check out this question and answers: http://stackoverflow.com/questions/4153517/how-exactly-does-the-androidonclick-xml-attribute-differ-from-setonclicklistene – jenzz May 26 '13 at 22:16

1 Answers1

1

There are a few parts to this question : performance, maintainability and personal preference.

  1. Performance: using the xml method imposes a performance penalty since the framework has to use reflection to call your class's method. Gingerbread and above should be fine (better jit) but before that the difference was noticeable.

  2. It is my belief that the xml method is less maintainable as it puts "code things" (method names) inside the presentation layer. Untangling which handler is set where requires diligent comments, which developers all too often forget to add.

  3. Similarly to 2, I believe that's it's much clearer to do field assignment (findViewById) and event handlers in the same place as I then have a "view initialization" area. Splitting it across files feels like torture to me. Using view/dependency injection is even better.

P.S. you don't have to assign the listeners to fields, it's cleaner to use anonymous classes that then call a single method of your activity/fragment.

Delyan
  • 8,881
  • 4
  • 37
  • 42