Android: Set up your Action Bar just once

Senza titolo-2
Several things related to the action bar can’t be defined in the xml and is pretty annoying having to set things up in each activity.
One easy and pretty simple way to avoid this is to specialize Activity class.
Often at the beginning of the Android programming experience is easy to don’t realize that all the Android framework is object oriented, altough acually it is and thus we can derive and specialize all its classes as any other.

This is pretty usefull in many situation but to be in the topic of this post here an example reltative to action bar:

public class MyBaseActivity extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);	

    	ActionBar ab = getActionBar();
    	ab.setCustomView(R.layout.actionbar_custom_layout);
        ab.setDisplayHomeAsUpEnabled(true);
        /* .. */
    }
}

Once we have defined our custom Activity we can derive all the others activity from it and calling the super method as we do with the Android usual Activity we go also through our custom activity method.

public class MyBaseActivity extends MyBaseActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);	
	
        /* Activity specific code */
		
    }
}

Afterall this is a pretty trivial example, anyway it may help to understand uses of inheritance. To be more general, and maybe more trivial, anytime you have a common behavior in different object it may be easiest to define it once in a super class.

Beside the Action Bar example this approach is usefull many times, and not only overriding onCreate methods but every overridable framework method, and also defining new ones that you may call in you derived class when needed, whathever they’re static or dynamic.

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *