Posts under ‘Android Development’

Android: How To Implement Option Menu In Activity or Dialog

Using Option Menu In Activity

To implement Option Menu in an Activity, we need to create a new custom Dialog class. The example code is given below, please see comments in the code for detail.

Step 1: Create a custom Menu Layout (xml file) in Menu Resources (res/menu). I named it my_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu
  xmlns:android="http://schemas.android.com/apk/res/android">
  
  <item 
      android:icon="@android:drawable/ic_menu_share"
      android:title="Option 1" 
      android:id="@+id/menu_option_one" 
   />

  <item 
      android:icon="@android:drawable/ic_menu_preferences" 
      android:title="Option 2" 
      android:id="@+id/menu_option_two" 
  />

  <item 
      android:icon="@android:drawable/ic_menu_info_details" 
      android:title="Option 3" 
      android:id="@+id/menu_option_three" 
  />
  
</menu>
Step 2: Define a custom Dialog class.
package com.chohdry.adnan.androidexamples;

import android.app.Activity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

public class OptionMenuWithActivity extends Activity {

	/*
	 * Override function onCreateOptionsMenu(Menu menu)
	 * Get menu inflater from activity
	 * Inflate layout (assign custom menu layout)
	 * Call super class's onCreateOptionsMenu(menu)
	 */
	//
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.my_menu, menu);

		return super.onCreateOptionsMenu(menu);
	}

	/**
	 * Override function onOptionsItemSelected(MenuItem item)
	 * Identify the item
	 * Call super class's onOptionsItemSelected(MenuItem item)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		if(item.getItemId()==R.id.menu_option_one){
			//do whatever you want
		}
		return super.onOptionsItemSelected(item);
	}
}

Using Option Menu In Dialog

Step 1 in implementation of Option Menu in a Dialog is same as above. For Step 2, class structure is different because here we need to extend our class from Dialog class rather Activity and also we need to override onMenuItemSelected(int featureId, MenuItem item) instead of onOptionsItemSelected(MenuItem item).

Step 2: Define a custom Dialog class.
package com.chohdry.adnan.androidexamples;

import android.app.Activity;
import android.app.Dialog;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

//Create a new class extended from default Dialog class
public class OptionMenuWithDialog extends Dialog {

	//Define activity type variable in class
	private Activity mActivity;

	/**
	 * Implement constructor (a custom or default passing Activity)
	 * Set class variable.
	 */
	public OptionMenuWithDialog(Activity activity) {
		super(activity, android.R.style.Theme_Translucent);
		mActivity = activity;

		//Customize your dialog here
	}

	/**
	 * Override function onCreateOptionsMenu(Menu menu)
	 * Get menu inflater from activity
	 * Inflate layout (assign custom menu layout)
	 * Call super class's onCreateOptionsMenu(menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		MenuInflater inflater = mActivity.getMenuInflater();
		inflater.inflate(R.menu.my_menu, menu);

		return super.onCreateOptionsMenu(menu);
	}

	/**
	 * Override function onMenuItemSelected(int featureId, MenuItem item)
	 * Identify the item
	 * Call super class's onMenuItemSelected(int featureId, MenuItem item)
	 */
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {

		if(item.getItemId()==R.id.menu_option_one){
			//do whatever you want
		}
		return super.onOptionsItemSelected(item);
	}
}

This code is available for public use on my GitHub. Download (or get using git) sample Android Examples Project from here https://github.com/adnanyousafch/android-examples.

Android: UI Navigation Using Back Button

You have developed a fine Android application, implemented tabbed design or have multiple screens and there are lots of UI screens that will be shown on various buttons’ clicks. Now for a good user experience you must keep track of UI screens previously opened in order to provide user with facility to go back to previous window (It is an application not website, so back button will not be available like browser). For this you will need to provide a button/image to go back on every screen and disable device’s back button (else it will close app if not handle to do another action) OR you can use back button OR provide both facilities (and I prefer both).

Solution:

  1. Have one class level variable which will define which screen to show on Back Button press (e.g. GO_TO).
  2. Have one class level constant for each screen, define any unique value for identification (e.g. MAIN, ONE, TWO, THREE).
  3. Make separate Methods/Functions to show each Screen.
  4. Set GO_TO variable to previous screen’s corresponding constant (e.g. “ScreenOne” is shown from button in “MainScreen”, so set GO_TO = MAIN in method of showing ScreenOne).
  5. Implement “onClick” to define button navigation.
  6. Override  ”onKeyDown” using conditions with help of GO_TO (see example code).
  7. Enjoy :-) .

Example Code:

package com.adnan.test;

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

public class TestDialogActivity extends Activity implements OnClickListener {

	private byte GO_TO = 0;
	private final byte CLOSE = -1;
	private final byte MAIN = 0;
	private final byte ONE = 1;
	private final byte TWO = 2;
	private final byte THREE = 3;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        showMainScreen();

        Button screenOneButton = (Button) findViewById(R.id.screen_one_btn);
        Button screenTwoButton = (Button) findViewById(R.id.screen_two_btn);
        Button screenThreeButton = (Button) findViewById(R.id.screen_three_btn);

        screenOneButton.setOnClickListener(this);
        screenTwoButton.setOnClickListener(this);
        screenThreeButton.setOnClickListener(this);
    }

    private void showMainScreen(){
    	GO_TO = CLOSE;
    	setContentView(R.layout.main);
    }

    private void showScreenOne(){
    	GO_TO = MAIN;

    	setContentView(R.layout.screen_one);

    	Button screenOneChild1Button = (Button) findViewById(R.id.screen_one_child1_btn);
        Button screenOneChild2Button = (Button) findViewById(R.id.screen_one_child2_btn);

        screenOneChild1Button.setOnClickListener(this);
        screenOneChild2Button.setOnClickListener(this);
    }

    private void showScreenTwo(){
    	GO_TO = MAIN;

    	setContentView(R.layout.screen_two);
    }

    private void showScreenThree(){
    	GO_TO = MAIN;

    	setContentView(R.layout.screen_three);

    	Button screenThreeChildButton = (Button) findViewById(R.id.screen_three_child_btn);
        screenThreeChildButton.setOnClickListener(this);
    }

    private void showScreenOneChild1(){
    	GO_TO = ONE;

    	setContentView(R.layout.screen_one_child1);
    }

    private void showScreenOneChild2(){
    	GO_TO = ONE;

    	setContentView(R.layout.screen_one_child2);
    }

    private void showScreenThreeChild(){
    	GO_TO = THREE;

    	setContentView(R.layout.screen_three_child);
    }

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.screen_one_btn:

			showScreenOne();
			break;
		case R.id.screen_two_btn:

			showScreenTwo();
			break;
		case R.id.screen_three_btn:

			showScreenThree();
			break;
		case R.id.screen_one_child1_btn:

			showScreenOneChild1();
			break;
		case R.id.screen_one_child2_btn:

			showScreenOneChild2();
			break;
		case R.id.screen_three_child_btn:

			showScreenThreeChild();
			break;
		default:
			break;
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		boolean disableEvent = false;

		if (event.getAction()==KeyEvent.ACTION_DOWN &amp;&amp; event.getKeyCode()==KeyEvent.KEYCODE_BACK) {
			if(GO_TO == MAIN) {

				showMainScreen();
				disableEvent = true;
			}else if(GO_TO == ONE) {

				showScreenOne();
				disableEvent = true;
			}else if(GO_TO == TWO) {

				showScreenTwo();
				disableEvent = true;
			}else if(GO_TO == THREE) {

				showScreenThree();
				disableEvent = true;
			}else if(GO_TO == CLOSE) {

				finish();
			}
		}
		return disableEvent;
	}
}

Android: How To Disable Back Button

In your application you might need to disable back button. Some handle back button operations by providing image/button on screen or by editing back key’s action listener. But if you don’t handle it or disable it User might find closing your application while trying to go back to previous screen.
NOTE: If you want to disable back key in entire application then don’t forget to provide explicit application close button.

Solution:

For the purpose you will need to attach OnKeyListener to your object, for example if you have a dialog, lets say “mainScreen” then:

mainScreen.setOnKeyListener(mainScreenKeyListener);

OnKeyListener mainScreenKeyListener = new OnKeyListener() {

    @Override
    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {

        boolean disableEvent = false;

        if (event.getKeyCode()==KeyEvent.KEYCODE_BACK) {

            disableEvent = true;

        }

        return disableEvent;
    }
};
/** 
* you can add "event.getAction()==KeyEvent.ACTION_DOWN" 
* to the condition to make it work on ACTION_DOWN specifically 
* or you can look up "KeyEvent" class to enable/disable/modify 
* behavior on various Buttons and Actions.
*/

Android: Disable Multi Tapping

So you have developed a very nice Android application, user taps a Button or Image on application and it shows another screen or do some action. Have you ever thought if user does not have patience for few hundred milliseconds or device is a bit slow due to all free applications installed from Android Market and in anticipation user kept taping until new screen doesn’t show up then what will happen? Yes the process against click will run as many times as number of taps.

Surely you won’t be willing to start another process while current process haven’t completed yet. Here are couple of tips to disable double tapping.

Enable/Disable All Clicks:

Make two functions in Class. 1st to disable onClick event on all clickable Buttons/Images using variableName.setEnabled(false) and 2nd to enbable onClick event for all clickable Buttons/Images using variableName.setEnabled(true). Call disable function as soon as user taps 1st time and call enable function after completion of that process or after showing screen or some dialogue.

[NOTE: This is Highly Recommended.]

Make Single View Object:

I will not dig down to android best practices but just to let you know that it is recommended to make separate classes for each screen and manage show(), hide() functions for better usage of views and dialogues. On Button/Image Click rather than creating new Object of Class every time all you need is to do is to define reference of it at Class Level in Class that is handling onClick event. Just put a null check where actually new Object is required to be initiated so the Object of new screen Class will be generated only once. Now implement hide() and show() methods in called class, use show() method to display and on closure of that screen just hide it using hide().

[NOTE: Hiding will keep the object alive in memory and it is not recommended.]

These are not only few solutions to the problem. There could be many more.

Android: Button/Image Pressed Effect

For the purpose you will have to design two images first. 1st for normal view and 2nd for clicked view.

  1. Design two images, 1 for normal view and other for clicked view in res\ drawable (i am naming 1st ‘button_normal.png’ and second ‘button_selected.png’).
  2. Create a new layout in res\layout,(i am naming it as ‘button_style.xml’).
  3. Place following code into new layout i.e. in button_style.xml.
  4. <?xml version="1.0" encoding="UTF-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    	<item android:drawable="@drawable/button_normal"/><!-- Normal Button View -->
    	<item android:state_pressed="true" android:drawable="@drawable/button_selected"/><!-- Pressed/Tapped Button View -->
    </selector>
    
  5. Your button view states have been created, you will now need to assign it to any button or image.
  6. Create a button in your Activity Layout and assign layout ‘button_style’ to its background.
  7. <Button 	android:background="@layout/button_style"
    		android:text="My Button"
    		android:id="@+id/my_btn" >
    </Button>
    
  8. In same way this effect can be applied to an Image.
  9. Enjoy.
about.me
Adnan Chohdry

Adnan Chohdry

IT and Software Professional

Top Viewed Posts
Top Viewed Pages
Get New Posts In Email
Please enter email address
counters