EVENTS HANDLING
Events
are a useful way to collect data about a user's interaction with interactive
components of Applications. Like button presses or screen touch etc.
The
Android framework maintains an event queue as first-in, first-out (FIFO) basis.Event Listeners
An
event listener is an interface in the View class that contains a
single callback method. These methods will be called by the Android framework
when the View to which the listener has been registered is triggered by user
interaction with the item in the UI.
Included
in the event listener interfaces are the following callback methods:
onClick()
From View.OnClickListener. This is called when the user either touches
the item (when in touch mode), or focuses upon the item with the
navigation-keys or trackball and presses the suitable "enter" key or
presses down on the trackball.
onLongClick()
From View.OnLongClickListener. This is called when the user either touches
and holds the item (when in touch mode), or focuses upon the item with the
navigation-keys or trackball and presses and holds the suitable
"enter" key or presses and holds down on the trackball (for one
second).
onFocusChange()
From View.OnFocusChangeListener. This is called when the user navigates onto
or away from the item, using the navigation-keys or trackball.
onKey()
From View.OnKeyListener. This is called when the user is focused on
the item and presses or releases a hardware key on the device.
onTouch()
From View.OnTouchListener. This is called when the user performs an
action qualified as a touch event, including a press, a release, or any
movement gesture on the screen (within the bounds of the item).
onCreateContextMenu()
From View.OnCreateContextMenuListener. This is called when a
Context Menu is being built (as the result of a sustained "long
click"). See the discussion on context menus in the Menus developer guide.
Example 1 : create new project
onClick()
activity_main.xml
<?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:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="open sajidtutorials" />
</LinearLayout>
OnClickActivity.java
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
public class OnClickActivity extends Activity {
Button
button;
@Override
public
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
public
void addListenerOnButton() {
button
= (Button) findViewById(R.id.button1);
button.setOnClickListener(new
OnClickListener() {
@Override
public
void onClick(View arg0) {
Intent intent =
new
Intent(Intent.ACTION_VIEW,
Uri.parse("http://sajidtutorials.blogspot.com/"));
startActivity(intent);
}
});
}
}
Screen Shots:
Example 2 onLongClick/Ontouch: create new project LongClickExample
MainActivity.java
package com. Long.click.example;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView myText = (TextView)findViewById(R.id.textView1);
final EditText myInput = (EditText)findViewById(R.id.editText1);
Button lButton = (Button) findViewById(R.id.buttonl);
ImageView imgv= (ImageView)findViewById(R.id.image);
ImageView
imgvv = (ImageView) findViewById(R.id.image1);
// -- register click event with
button ---
lButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
myText.setText(myInput.getText());
}
});
imgv.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v)
{
// TODO Auto-generated
method stub
Toast toast =
Toast.makeText(MainActivity.this,
"you
clicked ", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP
,10,140);
toast.show();
return true;
}
});
imgvv.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case
MotionEvent.ACTION_DOWN:
// PRESSED
Toast toast1 = Toast.makeText(MainActivity.this,
"you
pressed ", Toast.LENGTH_SHORT);
toast1.setGravity(Gravity.TOP
,10, 260);
toast1.show();
return true; // if you
want to handle the touch event
case MotionEvent.ACTION_UP:
// RELEASED
Toast toast2 = Toast.makeText(MainActivity.this,
"you
released ", Toast.LENGTH_SHORT);
toast2.setGravity(Gravity.TOP
,10, 260);
toast2.show();
return true; // if you
want to handle the touch event
}
return false;
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
activity_main.Xml
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.assignmentno6.MainActivity">
<TableRow
android:id="@+id/tableRow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<EditText
android:hint="@string/reminder"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/editText1"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
>
</EditText>
<Button
android:id="@+id/buttonl"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/Submit"
android:layout_marginLeft="10dp">
</Button>
</TableRow>
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display Name
Here :"
android:textColor="#000000"
android:layout_marginLeft="20dip">
</TextView>
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="50dip"
android:layout_gravity="center_horizontal"
>
<ImageView
android:id="@+id/image"
android:contentDescription="@string/content"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@drawable/
ic_launcher "
/>
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="50dip"
android:layout_gravity="center_horizontal">
<ImageView
android:id="@+id/image1"
android:contentDescription="@string/content"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@drawable/ic_launcher"
/>
</TableRow>
</TableLayout>
Screen Shots:
Example3 onKey: Create new Project
MainActivity.java
import
android.os.Bundle;
import
android.view.KeyEvent;
import
android.view.View;
import
android.view.View.OnKeyListener;
import
android.widget.EditText;
import
android.widget.Toast;
import
android.app.Activity;
public
class MainActivity extends Activity implements OnKeyListener {
private EditText userName;
private EditText password;
private String mUserName;
private String mPassword;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userName = (EditText)
findViewById(R.id.txt_name);
password = (EditText)
findViewById(R.id.password);
// set onkeyListner
userName.setOnKeyListener(this);
password.setOnKeyListener(this);
}
@Override
public boolean onKey(View v, int keyCode,
KeyEvent event) {
switch (v.getId()) {
case R.id.txt_name:
// keyup and "ENTER"
if ((event.getAction() ==
KeyEvent.ACTION_DOWN)
&& (keyCode ==
KeyEvent.KEYCODE_ENTER)) {
mUserName = userName.getText().toString();
if (mUserName.equals("")) {
Toast.makeText(this, "Enter user
name...",
Toast.LENGTH_SHORT).show();
} else
password.requestFocus();
}
break;
case R.id.password:
// keydown and "ENTER"
if ((event.getAction() ==
KeyEvent.ACTION_DOWN)
&& (keyCode ==
KeyEvent.KEYCODE_ENTER)) {
mPassword = password.getText().toString();
if (mPassword.equals(""))
Toast.makeText(this, "Enter
password...",
Toast.LENGTH_SHORT).show();
else
// show Toast Long time
Toast.makeText(
this,
"User name : " + mUserName +
" Password : "
+ mPassword,
Toast.LENGTH_LONG).show();
}
break;
}
return false;
}
}
activity_main.xml
<RelativeLayout
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"
tools:context=".EditTextKeyListener" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:textSize="20sp" />
<EditText
android:id="@+id/txt_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="@string/username"
>
<requestFocus />
</EditText>
<EditText
android:id="@+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/txt_name"
android:layout_below="@+id/txt_name"
android:layout_marginTop="24dp"
android:ems="10"
android:inputType="textPassword"
android:hint="@string/psass"
/>
</RelativeLayout>
ScreenShots:
Example 4 contextmenu: create new project
MainActivity.java
import
android.app.Activity;
import
android.content.Intent;
import
android.net.Uri;
import
android.os.Bundle;
import
android.view.ContextMenu;
import
android.view.ContextMenu.ContextMenuInfo;
import
android.view.MenuItem;
import
android.view.View;
import
android.widget.AdapterView;
import
android.widget.AdapterView.OnItemClickListener;
import
android.widget.LinearLayout;
import
android.widget.ListView;
public
class MainActivity extends Activity
{
ListView listViewSmartContacts;
ContactListAdapter contactListAdapter;
//ArrayList<String>
numberList;
String number;
public ShowSmartContactsActivity()
{
/// numberList=new
ArrayList<String>();
}
@Override
public void onCreate(Bundle
savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.show_contacts);
LinearLayout
layoutContacts=(LinearLayout)findViewById(R.id.layoutSmartContacts);
int
APILevel=android.os.Build.VERSION.SDK_INT ;
if(APILevel>=14)
{
layoutContacts.setBackgroundResource(R.color.Default);
}
listViewSmartContacts=(ListView)findViewById(R.id.listSmartContacts);
//getList();
contactListAdapter=new
ContactListAdapter(this);
listViewSmartContacts.setAdapter(contactListAdapter);
registerForContextMenu(listViewSmartContacts);
}
@Override
public void
onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Select The Action");
menu.add(0, v.getId(), 0,
"Call");
menu.add(0, v.getId(), 0,
"Send SMS");
}
@Override
public boolean
onContextItemSelected(MenuItem item)
{
AdapterView.AdapterContextMenuInfo
info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
String number;
try
{
number=new
ContactListAdapter(this).numberList.get(info.position);
if(item.getTitle()=="Call")
{
Intent
callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+number));
startActivity(callIntent);
}
else
if(item.getTitle()=="Send SMS")
{
Intent
smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address", number);
startActivity(smsIntent);
}
else
{return
false;}
return
true;
}
catch(Exception e)
{
return true;
}
}
}
Screen Shots