Android drop down pattern
OnNavigationlistener
Creating Drop Down navigation
Eclipse + ADT and Android studio both support this kind of navigation and we can find everything we need to implement it. We want to analyze the code generated automatically. To enable the drop down navigation in our Activity we can create a new project and we reach the last step before confirming everything we have:To enable the drop down navigation we have to get the Actionbar reference and the set the navigation type we want, in our case NAVIGATION_MODE_LIST. If we look at the code generated we notice:
// Set up the action bar to show a dropdown list.where at line 4 we enable our navigation type.
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
Implementing the navigation item
We need to create a list of item corresponding to the action we want to support. In other words we have to create a menu with different items. The drop down list is implemented like a Spinner. We know a Spinner is android view that displays one time at time and user can select one item among a list of items. So to create our drop down navigation list we need simply populate a spinner. To populate a spinner we need an Adapter, in our case a simple ArrayAdapter, so we have:ArrayList<String> itemList = new ArrayList<String>();
itemList.add("Section 1");
itemList.add("Section 2");
ArrayAdapter<String> aAdpt = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, itemList);
Looking at the code generated we notice that it is a little bit different form the one we have above because instead of this, it uses getActionBarThemedContextCompat. Looking at this method code we find out that it returns this for all the version below Ice Cream Sandwich and another value otherwise. This is used to maintain the compatibility with the all android version.
Now we have to assign our adapter to the Actionbar, we can do it using:
actionBar.setListNavigationCallbacks(aAddpt, this);
Notice that we used this as method parameter. This means that our activity has to implement an interface so that it gets notified when user picks an item.
Implementing ActionBar.OnNavigationListener
As we said in order to be notified when user selects an item we implements ActionBar.OnNavigationListener that has only one method to override:
@Override
public boolean onNavigationItemSelected(int position, long id) {
// Our logic
}
Now in this method we have to activate the right view according to the item selected by user. Usually we can use Fragment to enable the right UI. In this method we can instantiate a new fragment and replace the existing one with the new one.
Running the code we have:
You might be interested on:
Android Action Bar (ActionBar) Tab navigation
Android Action Bar (ActionBar) Tab navigation
0 comments:
Post a Comment