Handling Android Menu Events
Handling Android Menu Events
Application
Development
CHAPTER 4
Course Outcome
Apply various events handling processes on appropriate android
widgets for user interaction.
Event 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. You can
capture these events in your program and take appropriate action as per
requirements.
Android Event Management
•Event Listeners − An event listener is an interface in the View class that contains a single
callback method. This method 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.
•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.
•Event Handlers − When an event happens and we have registered an event listener for the
event, the event listener calls the Event Handlers, which is the method that actually handles
the event.
Event Listeners
& Event Event Handler Event Listener & Description
OnClickListener()
Handlers This is called when the user either clicks or touches
onClick() or focuses upon any widget like button, text, image
etc. You will use onClick() event handler to handle
such event.
OnLongClickListener()
This is called when the user either clicks or touches
onLongClick() or focuses upon any widget like button, text, image
etc. for one or more seconds. You will use
onLongClick() event handler to handle such event.
OnFocusChangeListener()
This is called when the widget looses its focus ie.
onFocusChange(
user goes away from the view item. You will use
)
onFocusChange() event handler to handle such
event.
OnKeyListener()
This is called when the user is presses or
releases a hardware key on the device.
onKey() You will use onKey() event handler to
Continue.. handle such event.
OnTouchListener()
This is called when the user presses the
key, releases the key, or any movement
onTouch() gesture on the screen. You will use
onTouch() event handler to handle such
event.
OnMenuItemClickListener()
This is called when the user selects a
onMenuItemClick() menu item. You will use
onMenuItemClick() event handler to
handle such event.
Continue….
onCreateContextMenuItemListener()
onCreateContextMenu() This is called when the context menu is
being built(as the result of a sustained
"long click)
OnClickListener()
[Link](getApplicationContext(), "Welcome",
Toast.LENGTH_LONG).show();
}
});
}
}
Touch Mode
Users can interact with their devices by using hardware keys or buttons or
touching the screen.
Touching the screen puts the device into touch mode. The user can then interact
with it by touching the on-screen virtual buttons, images, etc.
You can check if the device is in touch mode by calling the View class’s
isInTouchMode() method.
You can react to touch events in your custom views and your activities. Android
supports multiple pointers, e.g. fingers which are interacting with the screen. The
base class for touch support is the MotionEvent class which is passed to Views via the
onTouchEvent() method.
Continue…
When working on touch events we start by clicking a view and removing the gesture
(finger/stylus) then MotionEvent.ACTION_DOWN and MotionEvent.ACTION_UP is called
respectively.
When the initial touch happens on the ViewGroup and after intercepting when it moves to the
child, then MotionEvent.ACTION_CANCEL gets called on the ViewGroup and the touch event
dispatches to the children.
Now, everything depends on onInterceptTouchEvent() and its return value. Based on its return
value the dispatchTouchEvent is dependent, that if returns true the dispatcher is canceled, and
if it returns false then the dispatching of the touch event keeps going on until its used.
And onTouchEvent() if the return value is true, then it means the touch is handled and if it
returns false then it means the touch is not handled.
Coding
}
OnFocusChangeListener()
This is called when the widget looses its focus ie. user goes away from the
view item. You will use onFocusChange() event handler to handle such event.
public class MainActivity extends AppCompatActivity {
EditText t1,t2,t3;
@Override
protected void onCreate(Bundle
savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
t2=(EditText)findViewById([Link]
2);
[Link](new
[Link]() {
@Override
public void onFocusChange(View view,
boolean b) {
[Link]("Focus is Changed");
}
});
}
}
KeyListener
[Link](new [Link]() {
@Override
public boolean onKey(View view, int i, KeyEvent
keyEvent) {
if ((i == KeyEvent.KEYCODE_ENTER)) {
//coding
return true;
} else
return false;
}
});
Change the colour of edit Text
when enter key pressed
EditText t1,t2;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
// v=new LinearLayout(this);
t1=findViewById([Link]);
t2=findViewById([Link]);
[Link](new [Link]() {
@Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if ((i == KeyEvent.KEYCODE_ENTER)) {
[Link]();
[Link]([Link]);
return true;
} else
return false;
}
});
}
}
Menus in Android
A screen could have any number of widgets and you may optionally attach a
menu to any of those widgets.
Types of Menu
1. Option Menu
2. Context Menu
3. Popup Menu
Right click on resNewAndroid Resource Directory set resource type Menu and
click OK
Steps
Step 1: Open an Activity Class
Return true;
}
Handle Android Options Menu
Click Events
public boolean onOptionsItemSelected(MenuItem item) {
switch ([Link]()) {
case [Link]:
// do something
return true;
case [Link]:
// do something
return true;
default:
return [Link](item);
}
}
Example
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater m;
m = getMenuInflater();
[Link]([Link].menu11,menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = [Link]();
switch (id){
case [Link].item1:
[Link](getApplicationContext(),"Item 1 Selected",Toast.LENGTH_LONG).show();
return true;
case [Link].item2:
[Link](getApplicationContext(),"Item 2 Selected",Toast.LENGTH_LONG).show();
return true;
case [Link].item3:
[Link](getApplicationContext(),"Item 3 Selected",Toast.LENGTH_LONG).show();
return true;
default:
return [Link](item);
}
}
}
PopUp Menu
In android, Popup Menu displays a list of items in a modal popup window that is
anchored to the view. The popup menu will appear below the view if there is a
room or above the view in case if there is no space and it will be closed
automatically when we touch outside of the popup.
The android Popup Menu provides an overflow style menu for actions that are
related to specific content.
Implement
Popup in
Android
Create Menu
folder and popup
menu file in Res
<?xml version="1.0" encoding="utf-8"?
>
<menu
xmlns:android="[Link]
com/apk/res/android">
<item android:id="@+id/one"
android:title="One" />
<item android:id="@+id/two"
android:title="Two"/>
<item android:id="@+id/three"
android:title="Three"/>
</menu>
public class MainActivity extends AppCompatActivity {
Button b1;
[Link](savedInstanceState);
setContentView([Link].activity_main);
b1=(Button)findViewById([Link]);
[Link](new [Link]() {
Activity
//Inflating the Popup using xml file
[Link]().inflate([Link], [Link]());
[Link](new [Link]() {
return true;
} }); [Link]();
} }); }}
TOAST
A toast provides simple feedback about an operation
in a small popup. It only fills the amount of space
required for the message and the current activity
remains visible and interactive. Toasts automatically
disappear after a timeout.
Intents are like messages that activate software components (activities, services,
broadcast receivers)
An Intent may be explicit when it has exactly one target or implicit otherwise: it
just specifies the action the component should provide.
An intent can also be pending, meaning that some component will be activated in
the future
startActivity(i);
Fragments
Fragment represents a behavior or a portion of UI in an Activity. It is a kind of sub-
activity.
Display an icon on
the Status Bar (top screen)
Display a message in
the Notification Window
STATUS BAR
Notification
55
Android: Status Bar Notifications
56
Android: Status Bar Notifications
Define what will happen in case the user selects the notification
57
Android: Status Bar Notifications
58
Android: Status Bar Notifications
[Link] = [Link]([Link]
[Link] |= Notification.FLAG_INSISTENT;
59
Android: Status Bar Notifications
[Link] = 0xff00ff00;
[Link] = 300;
notification. ledOffMS = 1000;
[Link] |= Notification.FLAG_SHOW_LIGHTS;
60
Android: Status Bar Notifications
// Set two vibrations, one starting at time 0 and with duration equal to 100ms
long[] vibrate={0,100,200,300};
[Link] = vibrate;
61
Android: Status Bar Notifications
62
public class MainActivity extends Activity {
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
b=(Button)findViewById([Link]);
[Link](new [Link]() {
// @Override
public void onClick(View view) {
if([Link].SDK_INT>=Build.VERSION_CODES.O)
{
NotificationChannel nc=new
NotificationChannel("aa","aa",NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager mm=getSystemService([Link]);
[Link](nc);
}
[Link] n=new
[Link]([Link],"aa")
.setSmallIcon([Link].ic_baseline_flare_24)
.setContentTitle("Hello1")
.setContentText("Hello")
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat nm=[Link]([Link]);
[Link](222,[Link]());
}
});
}
}
Android: Toast Notifications
64
Android: Toast Notifications
Context context=getApplicationContext();
65
A dialog is a small window, that
prompts the user to make a decision
or enter additional information.
Progress
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main); Dialog
button = (Button) findViewById([Link]);
[Link](new [Link]() {
@Override
public void onClick(View v) {
progressDialog = new ProgressDialog([Link]);
[Link](100);
[Link]("Its loading....");
[Link]("ProgressDialog bar example");
[Link](ProgressDialog.STYLE_HORIZONTAL);
[Link]();
new Thread(new Runnable() {
@Override
public void run() {
try {
while ([Link]() <= [Link]()) {
[Link](200);
[Link]([Link]());
if ([Link]() == [Link]()) {
[Link]();
}
}
} catch (Exception e) {
[Link]();
}
}
}).start();
}
}
}, year, month, day);
[Link](new [Link]() {
@Override
public void onClick(View view) {
[Link]();
}
});
[Link]().setMaxDate([Link]());
@Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {