Event Handling by Specifying the Event Handler Method in XML: Layout File

If we specify the handler method in layout file (.xml) via the android:onClick attribute we do not need to implement a Listener interface or call setOnClickListener, just put the handler method in the main Activity.

We can supply different method names for different controls but this approach is limited to pass any arguments to Listener.

XML: Layout File Entry
res/layout/activity_event_ex2.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" 
        android:onClick="chooseAction"/>

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/btnCancel" 
        android:onClick="chooseAction"/>

</LinearLayout>

Main Activity
EventEx4Activity.java

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

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

	@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;
	}
	
	public void chooseAction(View v) {
		Button b = (Button)v;
	    String buttonText = b.getText().toString();
	    Toast.makeText(getApplicationContext(),
				buttonText+" Button Clicked", Toast.LENGTH_LONG).show();
		
	}
}

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

2,738` Total Views

Leave a Reply

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


2 + two =