Event Handling by Implementing Listener Interface

This is an android event handle example where main Activity implements the Listener interface. If the application has only a single control of that Listener type, this is the shortest and simplest of the approaches.

But if we want the handler to handle more than one control of the same Listener type, the onClick (or whatever) method would have to have to see which control was clicked.

res/layout/activity_event.ex1.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
 
    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/btnSave" />
 
    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/btnCancel" />
 
</LinearLayout>

EventEx3Activity.java

package com.bari.example.eventhandleexample;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class EventEx3Activity extends Activity implements OnClickListener{
	Button b1, b2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_event_ex1);
		b1 = (Button) findViewById(R.id.button1);
		b2 = (Button) findViewById(R.id.button2);
		b1.setOnClickListener(this);
		b2.setOnClickListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.event_ex1, menu);
		return true;
	}
	@Override
	public void onClick(View v) {
		Button b = (Button)v;
	    String buttonText = b.getText().toString();
	    Toast.makeText(getApplicationContext(),
				buttonText+" Button Clicked", Toast.LENGTH_LONG).show();
		
	}
}

Emulator Screenshot:
android_event_handle_implement_listener

You can download all android example from here.

 

admin

Hello! I am Md. Abdul Bari; founder and admin of javaknowledge; currently providing training as a J2EE faculty in The Computers Ltd. Dhaka, Bangladesh under an IT Scholarship project provided by IDB-BISEW. I am a self learner and passionate about training and writing. I am always trying my best to share my knowledge through my blog.

More Posts - Website

Follow Me:
TwitterFacebookGoogle Plus

3,149` Total Views

Leave a Reply

Your email address will not be published. Required fields are marked *


six × 7 =