Abstracting methods for Android. Show your Home/Up button in a better way

As I have started working with Android I have thought about contributing with the Internet community sharing all the knowledge that I acquire from what I am learning.

To begin I am going to introduce a really interesting practice, which is to abstract some methods that are used in almost all the classes into another class.

This is good for two reasons:

  • It’s easier to understand the code.
  • It’s easier to implement new classes

The first thing that I am sure that will be used in all your Android App’s Code is the home button. This is used to go back to the previous activity in your hierarchy.

implementing-navigation-up

The bottom from the left is the default up button.

For more information about it you can see:

showHomeButton Method

import android.app.ActionBar;
import android.app.Activity;

public final class Methods {
    public static void showHomeButton(Activity activity){
	if(android.os.Build.VERSION.SDK_INT>=11){
	    ActionBar actionBar = activity.getActionBar();
	    actionBar.setDisplayHomeAsUpEnabled(true);
	    actionBar.setHomeButtonEnabled(true);
	}
    }
}

As you can see the home button is implemented for API 11 or above, it is important to include it or It will not work for lower versions. Then you just have to get the Action Bar and set that the Home Button is enabled, it will show instantly the button (you don’t have to add it in the menu).

Then you just have to call Methods.showHomeButton(this); in the onCreate method of your activity.

To conclude, remember to put the parent activity name in your manifest and it’s equivalent for lower versions.

<activity
android:name="com.example.activities.Register"
android:parentActivityName="com.example.activities.LogIn" >

<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.activities.LogIn" />
</activity>

See you soon little androids!😀

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s