Handle Button Click Events

Event: When user clicks on the button event will be triggered and it will be processed by the OS. Then listener will receive the event and perform the specified on action on it.

Different ways to handle button clicks:

-> Handle from xml

In layout xml file while defining the button add onclick attribute.

Example:

<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”ListActivity”
android:id=”@+id/button4″
       android:onClick=”proceedToNext”
android:layout_below=”@+id/button3″
android:layout_alignStart=”@+id/button” />

Then write the method in activity for handle the click event.

public void proceedToNext(View v) {
if (v.getId() == R.id.button) {
Intent intent = new Intent(this, Communicate.class);
startActivity(intent);
}
if (v.getId() == R.id.button2) {
Intent intent = new Intent(this, TextHandle.class);
startActivity(intent);
}
if(v.getId() == R.id.button3){
Intent intent = new Intent(this, ListExample.class);
startActivity(intent);
}
if(v.getId() == R.id.button4){
Intent intent = new Intent(this, ListActivityEx.class);
startActivity(intent);
}
}

Here proceedToNext must take a View argument.
If we define multiple buttons for same method then we can find the which button is
clicked by comparing the button and argument which passed to proceedToNext method.
like shown above.

-> Using OnClickListener and override onClick method:

Implement the OnClickListener interface in activity and override the method onClick method. After button object is created then call setOnClickListner method.

Example:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button button= (Button) findViewById(R.id.button4);
    button.setOnClickListener(this);
}
@Override
public void onClick(View view) {
    Intent intent = new Intent(this, ListActivityEx.class);
    startActivity(intent);
}

-> Using anonymous class:

At the same time create a object for OnClickLister and implement the onClick method.

Example:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent = new Intent(MainActivity.this, ListActivityEx.class);
        startActivity(intent);
    }
});
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s