Android Event Handling

Android Event Handling

Android Event Handling are a good way to acquire data in regards to a user’s relationship with interactive the different parts of Applications. Like button presses or display touch etc. The Google android framework maintains an event queue as first-in, first-out (FIFO) basis. You are able to capture these events in your program and take appropriate action according to requirements.

android event handling

There are pursuing three ideas related to android Event Handling-

  • Android Event Listeners – An android event listener can be an user interface in the View category that contains an individual callback method. These procedures will be called by the Google android platform when the View to that your listener has been recorded is prompted by user discussion with that in the User Interface.
  • Android Event Listeners Registration – It is the procedure by which an event Handler gets listed with an android event Listener so the handler is named when the function Listener fires the event.
  • Android Event Handlers – When an event happens and we’ve registered a meeting listener for the event, the function listener calls the function Handlers, which is the technique that truly handles the event.

Android Event Listeners & Event Handlers

 

Android Event Handler     Android Event Listener     &   Description

onClick()              OnClickListener()

It is called when an client focuses, clicks or touches after any widget like phots,texts,buttons an so on. You use onClick() event handler to handle that  event.

onLongClick()     OnLongClickListener()

It is called when an client focuses, clicks or touches after any widget like phots,texts,buttons an so on, for just one or more mere seconds. You use onLongClick() event handler to handle that event.

onFocusChange()  OnFocusChangeListener()

That is called when the widget looses its emphasis ie. user goes away completely from the view item. You use onFocusChange() event handler to take care of such event.

onKey()                  OnFocusChangeListener()

It is called when an individual is targeted on that and presses or produces a hardware key on these devices. You use onKey() event handler to handle that event

onTouch()             OnTouchListener()

It is called when the main element is pressed by an individual, releases the main element, or any activity gesture on the display screen. You use onTouch() event handler to handle that event.

onMenuItemClick()      OnMenuItemClickListener()

It is called when an individual/user chooses a menu item. You use onMenuItemClick() event handler to handle that event.

onCreateContextMenu()     onCreateContextMenuItemListener()

That is called when the framework menu has been built(as the consequence of a suffered “long click)

android-event-handling-png

There are a lot more event listeners available as part of View class like OnHoverListener, OnDragListener etc which might be needed for the application. THEREFORE I recommend to send official documents for Android software development if you’re going to build up a complex apps.

Android Event Listeners Registration

Android Event Registration is the procedure by which an android  event Handler gets authorized with a event Listener so the handler is named when the event Listener fires the event. Though there are several confusing ways to join up your event listener for just about any event, but I’ll list down only top three ways, out which you may use some of them predicated on the situation.

  • By Using an Anonymous Inner Class
  • Activity class implements the Listener user interface.
  • By Using Layout record activity_main.xml to immediately designate event handler.

Below section shall provide you complete instances on all the three situations

Touch Mode

Users can connect to their devices by using hardware buttons or secrets or coming in contact with the display screen. Touching the screen puts these devices into touch mode. An individual can connect to it by touching the on-screen virtual buttons then, images, etc.You can examine if these devices is in contact mode by phoning the View class’s isInTouchMode() method.

android event handling

Focus

A widget is usually highlighted or shows a blinking cursor if it is in focus. This means that that it’s prepared to accept suggestions from user.

  • isFocusable() – it comes back true or false
  • isFocusableInTouchMode() – investigations to see if the view is focusable in contact method. (A view may be focusable when by using a hardware key however, not when these devices is in contact mode or touch mode)
android:foucsUp="@=id/button_l"

 

onTouchEvent()

public boolean onTouchEvent(motionEvent event){
   switch(event.getAction()){
      case TOUCH_DOWN:
      Toast.makeText(this,"you have clicked down Touch button",Toast.LENTH_LONG).show();
      break();
   
      case TOUCH_UP:
      Toast.makeText(this,"you have clicked up touch button",Toast.LENTH_LONG).show();
      break;
   
      case TOUCH_MOVE:
      Toast.makeText(this,"you have clicked move touch button"Toast.LENTH_LONG).show();
      break;
   }
   return super.onTouchEvent(event) ;
}

 

Android Event Handling Examples

There are several android event handling examples which are given below:

Android Event Listeners Registration Using an Anonymous Inner Class

Here you will generate an anonymous execution of the listener and you will be useful if each course is put on an individual control only and you have benefit to pass quarrels to event handler. In this process event handler methods can gain access to private data of Activity. No guide is required to call to Activity.

But if you applied the handler to several control, you’ll have to trim and paste the code for the handler in case the code for the handler is long, it creates the code harder to keep.

Following will be the simple steps showing how exactly we will utilize independent Listener class to register and record click event. In this way you can apply your listener for just about any other required event type.

Steps       Description

1     –         You use Android studio studio IDE to generate an Android software and name it as myapplication under a package deal com.example.myapplication as described in the Hello there World Example tutorial.

2     –         Modify src/MainActivity.java data file to include click event handlers and listeners for both control keys identified.

3      –        Modify the default content of res/design/activity_main.xml record to include Android os UI controls.

4      –        No need to declare default string constants.Google android studio takes attention default constants.

5        –      Run the application form to launch Android Os emulator and check the consequence of the changes done in the application form.

Following is the content of the modified main activity file src/com.example.myapplication/MainActivity.java. This file can include each of the fundamental lifecycle methods.

package com.example.myapplication;

public class MainActivity extends ActionBarActivity {
   private ProgressDialog progress;
   Button b1,b2;
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      progress = new ProgressDialog(this);
      
      b1=(Button)findViewById(R.id.button);
      b2=(Button)findViewById(R.id.button2);
      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            TextView txtView = (TextView) findViewById(R.id.textView);
            txtView.setTextSize(25);
         }
      });
      
      b2.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            TextView txtView = (TextView) findViewById(R.id.textView);
            txtView.setTextSize(55);
         }
      });
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
   }
   
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      
      int id = item.getItemId();
      
      //noinspection SimplifiableIfStatement
      if (id == R.id.action_settings) {
         return true;
      }
      return super.onOptionsItemSelected(item);
   }
}

 

Following will be the content of res/layout/activity_main.xml file

<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"
   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=".MainActivity">
   
   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Event Handling "
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="30dp"/>
      
   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Andro Development "
      android:textColor="#ff87ff09"
      android:textSize="30dp"
      android:layout_above="@+id/imageButton"
      android:layout_centerHorizontal="true"
      android:layout_marginBottom="40dp" />
      
   <ImageButton
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageButton"
      android:src="@drawable/abc"
      android:layout_centerVertical="true"
      android:layout_centerHorizontal="true" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Small font"
      android:id="@+id/button"
      android:layout_below="@+id/imageButton"
      android:layout_centerHorizontal="true" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Large Font"
      android:id="@+id/button2"
      android:layout_below="@+id/button"
      android:layout_alignRight="@+id/button"
      android:layout_alignEnd="@+id/button" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Hello World!"
      android:id="@+id/textView"
      android:layout_below="@+id/button2"
      android:layout_centerHorizontal="true"
      android:textSize="25dp" />
      
</RelativeLayout>

 

Following will be the content of res/values/strings.xml to define two new constants

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">myapplication</string>
   <string name="action_settings">Settings</string>
</resources>

 

Following is the default content of AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.myapplication"
   android:versionCode="1"
   android:versionName="1.0" >
   
   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="22" />
      
   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.myapplication.MainActivity"
         android:label="@string/app_name" >
      
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      
      </activity>
      
   </application>
</manifest>

 

How about we attempt to run our myapplication application we simply developed. I accept you had made your AVD while doing environment setup. To run the application from Android studio, open one of your project activity file and snap Run Android Studio  symbol from the tool bar. Android Studio installs the application on your AVD and begins it and if all is well with your set-up and application, it will show taking after Emulator window

android event handling

You make an effort to select two keys now, one at a time therefore you shall notice that font of the Hello World word changes, which is really because registered click event handler method has been called against each and every click event.

Android Event Handling Exercise

I’ll recommend to try writing different event handlers for different event types and understand exact difference in several event types and their android event handling. Happenings related to menu, spinner, pickers widgets are little different nonetheless they are based on the same concepts as explained above also.