UI Notification Listeners
×
Home Courses Community Support
Gray Matter

First Step Towards Android: Introduction »

Understanding Activities and Intents »

Hands On With UI Designing In Android (Controls-Views,Widgets and Layouts) »

Updating... »

UI Notification Listeners

Users interact with your UI at two levels: the activity level and the views level. At the activity level, the Activity class exposes methods that you can override. Some common methods that you can override in your activities include the following:

Methods Description
onKeyDown Called when a key was pressed and not handled by any of the views contained
within the activity
onKeyUp Called when a key was released and not handled by any of the views contained
within the activity
onMenuItemSelected Called when a panel’s menu item has been selected by the user
onMenuOpened Called when a panel’s menu is opened by the user


Overriding Methods Defined in an Activity

To understand how activities interact with the user, let’s start off by overriding some of the methods defined in the activity’s base class and learn how they are handled when the user interacts with the activity.

follow these steps :-

step1: Create a new Android project and name it UIActivity.

step2: Now we will modify activity_main.xml file. So add the following code into activity_main.xml file-

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    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:layout_width="214dp"
	android:layout_height="wrap_content"
	android:text="Your Name"
	/>
	<EditText
	android:id="@+id/txt1"
	android:layout_width="214dp"
	android:layout_height="wrap_content"
	/>
	<Button
	android:id="@+id/btn1"
	android:layout_width="106dp"
	android:layout_height="wrap_content"
	android:text="OK"
	/>
	<Button
	android:id="@+id/btn2"
	android:layout_width="106dp"
	android:layout_height="wrap_content"
	android:text="Cancel"
	/>

</LinearLayout>

step3: Now we will modify MainActivity.java file. So add the following code into MainActivity.java file-

package com.example.uiactivity;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.KeyEvent;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
    switch (keyCode)
    {
    case KeyEvent.KEYCODE_DPAD_CENTER:
    Toast.makeText(getBaseContext(),
    "Center was clicked",
    Toast.LENGTH_LONG).show();
    break;
    case KeyEvent.KEYCODE_DPAD_LEFT:
    Toast.makeText(getBaseContext(),
    "Left arrow was clicked",
    Toast.LENGTH_LONG).show();
    break;
    case KeyEvent.KEYCODE_DPAD_RIGHT:
    Toast.makeText(getBaseContext(),
    "Right arrow was clicked",
    Toast.LENGTH_LONG).show();
    break;
    case KeyEvent.KEYCODE_DPAD_UP:
    Toast.makeText(getBaseContext(),
    "Up arrow was clicked",
    Toast.LENGTH_LONG).show();
    break;
    case KeyEvent.KEYCODE_DPAD_DOWN:
    Toast.makeText(getBaseContext(),
    "Down arrow was clicked",
    Toast.LENGTH_LONG).show();
    break;
    }
    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;
    }
    
    
}

step4: Now Press F11 key to debug the application on the Android Emulator or on the device. Let's see the output window now.


 

When the activity is loaded, type some text into it, as shown on the left of Figure. Next, click the down arrow key on the directional pad. Observe the message shown on the screen, as shown in the black area on the right of Figure.

With the OK button in focus, press the center button in the directional pad. Observe that the message “Center was clicked” is not displayed. This is because the Button view itself is handling the click event. Hence the event is not caught by the onKeyDown() method. However, if none of the views is in focus at the moment (you can achieve this by clicking on the background of the screen), then pressing the center key will show the “Center was clicked” message (Figure).


 

Registering Events for Views

Views can fire events when users interact with them. For example, when a user touches a Button view, you need to service the event so that the appropriate action can be performed. To do so, you need to explicitly register events for views. Using the same example discussed in the previous section, recall that the activity has two Button views; therefore, you can register the button click events using an anonymous class as shown here:

follow these steps :-

step1: We will modify MainActivity.java file So add the following code into MainActivity.java file-

package com.example.uiactivity;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
      //---the two buttons are wired to the same event handler---
        Button btn1 = (Button)findViewById(R.id.btn1);
        btn1.setOnClickListener(btnListener);
        Button btn2 = (Button)findViewById(R.id.btn2);
        btn2.setOnClickListener(btnListener);
    }
    
  //---create an anonymous class to act as a button click listener---
    private OnClickListener btnListener = new OnClickListener()
    {
    public void onClick(View v)
    {
    	Toast.makeText(getBaseContext(),
    	((Button) v).getText() + " was clicked",
    	Toast.LENGTH_LONG).show();
    	}
    	};
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
    switch (keyCode)
    {
    case KeyEvent.KEYCODE_DPAD_CENTER:
    Toast.makeText(getBaseContext(),
    "Center was clicked",
    Toast.LENGTH_LONG).show();
    break;
    case KeyEvent.KEYCODE_DPAD_LEFT:
    Toast.makeText(getBaseContext(),
    "Left arrow was clicked",
    Toast.LENGTH_LONG).show();
    break;
    case KeyEvent.KEYCODE_DPAD_RIGHT:
    Toast.makeText(getBaseContext(),
    "Right arrow was clicked",
    Toast.LENGTH_LONG).show();
    break;
    case KeyEvent.KEYCODE_DPAD_UP:
    Toast.makeText(getBaseContext(),
    "Up arrow was clicked",
    Toast.LENGTH_LONG).show();
    break;
    case KeyEvent.KEYCODE_DPAD_DOWN:
    Toast.makeText(getBaseContext(),
    "Down arrow was clicked",
    Toast.LENGTH_LONG).show();
    break;
    }
    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;
    }
    
    
}

step2: Now Press F11 key to debug the application on the Android Emulator or on the device. Let's see the output window now.

If you now press either the OK button or the Cancel button, the appropriate message will be displayed (see Figure), proving that the event is wired up properly.
event for the EditText view:


 

Besides defining an anonymous class for the event handler, you can also define an anonymous inner class to handle an event. The following example shows how you can handle the onFocusChange() event for the EditText view:

follow these steps :-

step1: We will modify MainActivity.java file So add the following code into MainActivity.java file-

package com.example.uiactivity;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
      //---the two buttons are wired to the same event handler---
        Button btn1 = (Button)findViewById(R.id.btn1);
        btn1.setOnClickListener(btnListener);
        Button btn2 = (Button)findViewById(R.id.btn2);
        btn2.setOnClickListener(btnListener);
        EditText txt1 = (EditText)findViewById(R.id.txt1);
      //---create an anonymous inner class to act as an onfocus listener---
      txt1.setOnFocusChangeListener(new View.OnFocusChangeListener()
      {
      @Override
      public void onFocusChange(View v, boolean hasFocus) {
      Toast.makeText(getBaseContext(),
      ((EditText) v).getId() + " has focus - " + hasFocus,
      Toast.LENGTH_LONG).show();
      }
      });
    }
    
  //---create an anonymous class to act as a button click listener---
    private OnClickListener btnListener = new OnClickListener()
    {
    public void onClick(View v)
    {
    	Toast.makeText(getBaseContext(),
    	((Button) v).getText() + " was clicked",
    	Toast.LENGTH_LONG).show();
    	}
    	};
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
    switch (keyCode)
    {
    case KeyEvent.KEYCODE_DPAD_CENTER:
    Toast.makeText(getBaseContext(),
    "Center was clicked",
    Toast.LENGTH_LONG).show();
    break;
    case KeyEvent.KEYCODE_DPAD_LEFT:
    Toast.makeText(getBaseContext(),
    "Left arrow was clicked",
    Toast.LENGTH_LONG).show();
    break;
    case KeyEvent.KEYCODE_DPAD_RIGHT:
    Toast.makeText(getBaseContext(),
    "Right arrow was clicked",
    Toast.LENGTH_LONG).show();
    break;
    case KeyEvent.KEYCODE_DPAD_UP:
    Toast.makeText(getBaseContext(),
    "Up arrow was clicked",
    Toast.LENGTH_LONG).show();
    break;
    case KeyEvent.KEYCODE_DPAD_DOWN:
    Toast.makeText(getBaseContext(),
    "Down arrow was clicked",
    Toast.LENGTH_LONG).show();
    break;
    }
    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;
    }
    
    
}

step2: Now Press F11 key to debug the application on the Android Emulator or on the device. Let's see the output window now.

As shown in Figure, when the EditText view receives the focus, a message is printed on the screen.

 

← Preview

Creating UI Of An Application Via Code

Next →

Dynamic User Interfaces (Concept Of Fragments)

NOTES

Our mission is to provide highly effective and quality education via innovative solutions. Geeksdemy look forward to bridge the gap between in-demand technology and academics in order to deliver innovative, easy, interesting and affordable learning across the Globe.

Courses

  • Python
  • Game Development with Unity 3D
  • Arduino
  • PCB & Circuit Designing
  • Robotics and Embedded C
  • 8051/8052 Embedded Systems
  • QuadCopter & UAV
  • MATLAB with Robotics
  • Raspberry Pi
Learn On the Go!
Get the Android App
Get the iOS App