android:onClick – Binding a UI directly to Controller.

June 27th, 2011  | Tags:

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.

  1. Eduardo
    July 1st, 2011 at 15:57
    #1

    Olá, Jair!

    Tudo bem?

    Gostaria de te fazer um convite relacionado ao Java.

    Caso tenha interesse, aguardo seu contato.

    Abraços,
    Eduardo

  2. July 1st, 2011 at 19:46
    #2

    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.

TOP