Set button click event handler - Tuong-Nguyen/Android GitHub Wiki

There are several ways for setting a handler for button's click event (or other events). We look at 2 common ways:

Define handler in layout:

<Button
   android:id="@+id/my_btn"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Click me"
   android:onClick="onBtnClicked">
</Button>

Use setOnClickListener:

Button newPicButton = (Button)findViewById(R.id.my_btn);
newPicButton.setOnClickListener(btnListener);

With this option, we need to define inner class for implementing the Listener which makes the code harder to understand. If there are many buttons, multiple inner classes are created.

Therefore, I prefer Option 1.

⚠️ **GitHub.com Fallback** ⚠️