title: Best way to handle events in Android
body: <p>I know this seems like a duplicate question, but i was really unable to find a good answer on the related topic.</p>
  
  <p>There are tons of questions about what is the best way to handle an <code>OnClick</code> event of a <code>Button</code>.<br>
  Here are some of the options i came across:</p>
  
  <h3>1 - Defining a listener programatically on the <code>OnCreate</code> method:</h3>
  
  <pre><code>button.setOnClickListener(new OnClickListener(){
      @Override
      public void onClick(View v) {
          //do stuff
      }
  });
  </code></pre>
  
  <hr>
  
  <h3>2 - Setting the <code>android:OnClick</code> property on the XML:</h3>
  
  <pre><code>&lt;Button android:id="@+id/btnDelete"
      ...
      android:OnClick="btnDelete_OnClick"/&gt;
  </code></pre>
  
  <hr>
  
  <h3>3 - Implementing the <code>OnClickListener</code> interface on the <code>Activity</code> class and passing a self reference to the Button:</h3>
  
  <pre><code>public class MainActivity extends Activity implements OnClickListener{
      @Override
      public void onClick(View v) {
          //do stuff
      }
  
      protected void onCreate(Bundle savedInstanceState) {
          ...
          button.setOnClickListener(this);
      }
  }
  </code></pre>
  
  <hr>
  
  <h3>4 - Create a field with the <code>OnClickListener</code> type:</h3>
  
  <pre><code>private OnClickListener onClickHandler = new OnClickListener(){
  
      @Override
      public void onClick(View v) {
          //stuff
      }
  };
  
  protected void onCreate(Bundle savedInstanceState) {
      ...
      button.setOnClickListener(onClickHandler);
  }
  </code></pre>
  
  <hr>
  
  <p>When it comes to a <code>Button</code> and the <code>OnClick</code> event, I would always prefer defining it on the XML, it is just more clean.</p>
  
  <p>But what about other events like the <code>OnItemClick</code> from the <code>ListView</code> or the <code>OnTimeSet</code> from the <code>TimePickerDialog</code>? There is no property I can see for setting it on the XML. I think that implementing the Listener interface is a pretty clean solution, but that would mean I can only implement it once, and if I have two equal Views I would have to handle their events in the same place. If I use option 2 or 4, it would probably get quite messy when handling several events from different Views from the UI.</p>
  
  <p>I would like to see other opinions on this subject, if there are any other options of implementation for event handling. Is there really an alternative that could be defined as the better one or is it just a personal matter of each programmer?</p>