One of the most common task during UI design is handling the user clicks, usually on buttons. Android provides two alternative ways to handle user click: one using code and other using XML during the layout definition.
To make things very simple let’s suppose we have a button in our layout and we want to handle user clicks. As said before there are two ways:
- implements View.OnClickListener
- declare the method in XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextButton"
</LinearLayout>
If we use the first method we have to implements an interface called View.OnClickListner or we can use an anonym interface implementation that looks like:
// We retrieve button reference inside the layout
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Implements our code do handle user click
}
});
So as you can notice, we have first get the button reference using the method findViewById and then set the listener. These lines of code have to be repeated for every button inside the layout we want to handle.
There is another method that can be use and is to declare that our Activity implements the interface View.OnClickListener.In this case we have:
public class SurvivingClickActivity extends Activity implements View.OnClickListener {
. . .
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(this);
@Override
public void onClick(View v) {
int id = v.getId();
switch(id) {
case R.id.button1: // execeute our code
....
}
}
}
The View.OnClickListener requires to implement a method called onClick, where we have to chose which button was clicked by the user. To do it, we first get the View id and the we compare it with the buttons we want to handle.
The last strategy is declare the method that has to be called, when user clicks on the button, directly inside the XML like that:
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextButton"
android:onClick="executeHello"/>
Using the attribute android: onClick we declare the method name that has to be present on the parent activity. So we have to create this method inside our activity like that:
public void executeHello(View v) {
Toast.makeText(this, "Hello World", Toast.LENGTH_LONG).show();
}
Analyzing the three method shown above, of course the last one is the most elegant and the shortest too. The others two methods require too much code to be implemented and makes the activity class code too messy.
0 comments:
Post a Comment