Вы находитесь на странице: 1из 22

Bahria University Karachi Campus

CSC- 341
Mobile Application Development

Lecturer
M Talha Alam

https://sites.google.com/view/mtalhaalam
Bahria University Karachi Campus

LECTURE 5
LISTENERS

OUTLINE

• Working of listeners and events


• Types of listeners
Bahria University Karachi Campus

Event Listener

• What is event listener?

• Why we need this?

• How to use Event listener?


Bahria University Karachi Campus

Event Listener
• Events are a useful way to collect data about a user's
interaction with interactive components of your app,
like button presses or screen touch etc.

• The Android framework maintains an event queue


into which events are placed as they occur and then
each event is removed from the queue on a first-in,
first-out (FIFO) basis. You can capture these events in
your program and take appropriate action as per
requirements.
Bahria University Karachi Campus

Event Listener
• In the figure there is an activity and a button on it.
• When user clicked/ press the “Click Me” button an event generated and we
toast a text.
• So it is useful to handle user interaction as well as navigation according to user
interaction

After Clicking button


Bahria University Karachi Campus

Some types of Event Listener


Bahria University Karachi Campus

Event Listeners Registration


• Event Registration is the process by which an Event
Handler gets registered with an Event Listener so that the
handler is called when the Event Listener fires the event.

• Some way of event listeners registration-


1 Using an Anonymous Inner Class
2 Activity class implements the Listener interface.
3 Using Layout file activity_main.xml to specify event handler
directly.
Bahria University Karachi Campus

Using an Anonymous Inner Class


• Create an anonymous implementation of the listener.
• Useful if each class is applied to a single control only and you have
advantage to pass arguments to event handler.
• In this approach event handler methods can access private data of
Activity. No reference is needed to call to Activity.

Disadvantage
• If there are more than one control, you have to cut and paste the
code for the handler and if the code for the handler is long, it makes
the code harder to maintain
Bahria University Karachi Campus

Example
• Add a button in xml file

<Button
android:id="@+id/button1"
android:layout_height="wrap_content
"
android:layout_width="match_parent"
android:text="Click Me"/>

• Initialize it from java file

Button clickMe = (Button) findViewById(R.id.button1);


Bahria University Karachi Campus

Example
• Register click event with button
clickMe.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{

//write your code here


Toast.makeText(“getApplicationContext()”,
”You clicked a
button”,Toast.LENGTH_LONG).show();

}
}
);
Bahria University Karachi Campus

Using the Activity Implements Listener


Interface
 Activity class implements the Listener interface and put
the handler method in the main Activity and then call
setOnClickListener(this).

 This approach is fine if your application has only a single


control of that Listener type otherwise have to do further
programming to check which control has generated event.

 Second you cannot pass arguments to the Listener so,


again, works poorly for multiple controls.
Bahria University Karachi Campus

Example
• Implements onClickListener callback

<Button
android:id="@+id/button1"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text=“First Button"/>

<Button
android:id="@+id/button2"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text=“Second Button"/>

• Implements onClickListener() to MainActivity


Bahria University Karachi Campus

Example
• Implements onClickListener() CallBack which is onCLick()

public void onClick(View v)


{ if(v.getId() == R.id.button1)
{
// write your code here
return;
}
if(v.getId() == R.id.button2)

// write your code here


return;
}
}
Bahria University Karachi Campus

Using Layout file activity_main.xml


 Put your event handlers in Activity class without implementing a Listener interface or call to
any listener method.

 Rather you will use the layout file (activity_main.xml) to specify the handler method via the
android:onClick attribute for click event.

 Can be control click events differently for different control by passing different event
handler methods.

 The event handler method must have a void return type and take a View as an argument.

 The method name is arbitrary, and the main class need not implement any particular
interface.

 This approach does not allow to pass arguments to Listener and for the Android developers
it will be difficult to know which method is the handler for which control until they look
into activity_main.xml file.
Bahria University Karachi Campus

Example
• Used android:onClick attribute to specify a callback function

<Button
android:id="@+id/button1"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text=“First Button“
android:onClick=“method1” />

<Button
android:id="@+id/button2"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text=“Second Button“
android:onClick=“method2” />
Bahria University Karachi Campus

Example
• Implements onClickListener() CallBack which is onCLick()
public void method1(View v)
{
// write your handler code here
return;
}

//--- Implement the event handler for the second


button. public void method2(View v)
{
// write your handler code here
return; }
Bahria University Karachi Campus

EXAMPLE CODE

The example below shows how to register an on-click listener for a Button.
// Create an anonymous implementation of OnClickListener
private OnClickListener mCorkyListener = new
OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
}
};

protected void onCreate(Bundle savedValues) {


...
// Capture our button from layout
Button button = (Button)findViewById(R.id.corky);
// Register the onClick listener with the implementation
above
button.setOnClickListener(mCorkyListener);
...
}
Bahria University Karachi Campus

You may also find it more convenient to implement OnClickListener as a part


of your Activity. This will avoid the extra class load and object allocation. For
example:

public class ExampleActivity extends Activity implements


OnClickListener {
protected void onCreate(Bundle savedValues) {
...
Button button = (Button)findViewById(R.id.corky);
button.setOnClickListener(this);
}

// Implement the OnClickListener callback


public void onClick(View v) {
// do something when the button is clicked
}
...
}
Bahria University Karachi Campus

EXAMPLE to display current time by using listener

• Open your default activity file (Ex: ButtonTutorialActivity.java)


• Declare two global variables

Button btnCTime;
EditText txtCTime;

• import respective packages

import android.widget.Button;
import android.widget.EditText;

• Link these variables to the layout in OnCreate() as follows

btnCTime=(Button)findViewById(R.id.btnGenCurTime);
txtCTime=(EditText)findViewById(R.id.txtShowCurTime);
Bahria University Karachi Campus

• We don’t want the OnScreenKeyBoard to appear when the cursor is on


EditText so, let disable this.

txtCTime.setInputType(InputType.TYPE_NULL);
</li>
<li>Set the OnClickListener for the Button

btnCTime.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View vw) {

}
});

• import the package for OnClickListener

import android.view.View.OnClickListener;
Bahria University Karachi Campus

• Now do the logic inside onClick() to show the current time

txtCTime.setText(new Date().toString());

• You need to import java package for using Date

import java.util.Date;

• Finally, the default activity file should look like as java file in next
slide.
Bahria University Karachi Campus
package com.suvendu.tutorials.button;
import java.util.Date;
import android.app.Activity;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class ButtonTutorialActivity extends Activity {


Button btnCTime;
EditText txtCTime;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnCTime=(Button)findViewById(R.id.btnGenCurTime);
txtCTime=(EditText)findViewById(R.id.txtShowCurTime);
txtCTime.setInputType(InputType.TYPE_NULL);
btnCTime.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View vw) {
txtCTime.setText(new Date().toString());
}
}); }}

Вам также может понравиться