android:onClick – Binding a UI directly to Controller.
If you’re familiar with Android, probably you have already created a button on the user interface and implemented a controller method to respond to this button’s action. This can be done through the OnClickListener interface and its onClick(View) method. A example below:
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class TesteApp extends Activity implements OnClickListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); View view = findViewById(R.id.button1); view.setOnClickListener(this); } @Override public void onClick(View v) { //Implements the action over here. } } |
On line 1, we used OnClickListener interface. This interface provides us the onClick(View) method. Also, on line 6 and 7, we set up the Listener to the Button widget.
Since Android version 1.6 (API level 4), Android offers us an android:onClick UI Method. Using this approach, you do not need to implement the OnClickListener interface and also you do not need to implement the static onClick(View) method. Rather than, you can bind the android:onClick method directly to a method on the Activity. See the example below:
User Interface – main.xml
<Button android:text="Click me" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="buttonPressed"></Button> |
In the UI above, we set up the onClick to a method called buttonPressed.
Java class – Activity
1 2 3 4 5 6 7 8 9 10 | public class TesteApp extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void buttonPressed(View v) { //Implements the action over here. } } |
As you can see, the Activity above does not implement the OnClickListener. Also, the widget does not need to set up its Listener pragmatically. This way you write less code and your class get cleaner.
As far as I know, both ways work similar. There’s no performance issue or anything else. However the OnClickListener interface provides more methods than onClick. So, if you only need the onClick function, I advice you to use the android:onClick. If you need anything else, I advice you to implement the OnClickListener interface.
If you have any question, fell free to leave your comment below.

Brazilian guy, IT Specialist, Linux and Mac User. Work with Java/JEE and IBM Products, such as: WebSphere and DB2. Like studying Ruby, Android and IOS. Also, I like playing tennis, however I am not good enough. Write a post in this blog once a year. Follow me on twitter if you understand portuguese: @jairrillo.
Olá, Jair!
Tudo bem?
Gostaria de te fazer um convite relacionado ao Java.
Caso tenha interesse, aguardo seu contato.
Abraços,
Eduardo
Ola Eduardo, tudo bom?
Me envia um email jrjuniorsp (at) yahoo (dot) com (dot) br. Ou me add no gtalk jairrillo (at) gmail (dot) com.