How to handle a button being clicked in Android?
<p>In Android there seems to be 3 common ways of handling button clicks, how much difference is there between the methods? And are any of them 'better' in some way?</p>

<p>The three methods I keep seeing are:</p>

<p><strong>Anonymous class</strong></p>

<p>Find the button by it's ID, then pass a new anonymous class to <code>setOnClickListener</code>, e.g. in <code>onCreate</code></p>

<pre><code>findViewById(R.id.myButton).setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        // .. Whatever
    }
});
</code></pre>

<p><strong>Implement OnClickListener</strong></p>

<p>Implement <code>OnClickListener</code> and pass <code>this</code> to <code>setOnClickListener</code>, then use a switch statment based on the button ID, e.g. in <code>onCreate</code></p>

<pre><code>findViewById(R.id.myButton).setOnClickListener(this);
</code></pre>

<p>and implement <code>onClick</code> like</p>

<pre><code>public void onClick(View v) {
    switch(v.getId()) {
        case R.id.myButton:
            // ... whatever ...
            break;
    }
}
</code></pre>

<p><strong>Use onClick XML atribute</strong></p>

<p>In the XML layout for your activity, instead of giving your button an ID, use <code>onClick</code> like this:</p>

<pre><code>&lt;Button 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:onClick="buttonClicked" 
    android:text="Button" /&gt;
</code></pre>

<p>Then have a <code>buttonClicked</code> method in your Acitiviy like this:</p>

<pre><code>public void buttonClicked(View v) {
    // ... whatever ...
}
</code></pre>

<p>At the moment I tend to use the XML attribute, but that's just because it involves the least amount of code. When should I use the other methods?</p>
