OnClick Listeners for Buttons in Android Studio - Java

OnClick Listeners for Buttons in Android Studio - Java

Two ways to set OnClickListeners

As a beginner in Android development I have found two useful ways to setting OnClickListeners for buttons under Java.

First way: set the OnClickListener directly in the XML file

Sample code for XML file - notice the "android:onClick="ButtonMethod" attribute in the last line of the code snippet.

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Your button text here"
        android:onClick="ButtonMethod"/>

Define in the Java activity file the button method from the XML file:

public void ButtonMethod(View view) {
        //Code here executes after the user presses button
    }

Second way: set the OnClickListener directly in the Java Activity File

Sample code for the Java activity file - notice the declaration of the Button element, its 'findViewbyId' method (the id being defined in the XML file beforehand) and the 'setonClickListener' method, that takes 'View.OnClickListener' as argument. The code therefore creates an instance of View.OnClickListener and wires the listener to the button. Further the method 'onClick(View v)' specifies the behavior of the system once the button is pressed.

public class MyActivity extends Activity {
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);

         setContentView(R.layout.content_layout_id);

         Button button = findViewById(R.id.button_id);
         button.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 // Code here executes after the user presses button
             }
         });
     }
 }

Advantages and Disadvantages of Use:

The first way of handling buttons is in my view easier and more straight forward, while the second allows you to define button behavior for all your button instances (no need for duplicate code in the XML file for buttons with similiar behavior).

Hope this helps.