Android Open Source - ExpandableListDemoApp Navigation Drawer Fragment






From Project

Back to project page ExpandableListDemoApp.

License

The source code is released under:

MIT License

If you think the Android project ExpandableListDemoApp listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package de.frost.david.android.fragments;
/*  w  w w . j av  a 2s  .c om*/

import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.frost.david.android.R;
import de.frost.david.android.adapters.DrawerExpandableAdapter;
import de.frost.david.android.model.Category;
import de.frost.david.android.model.SubCategory;

/**
 * Fragment used for managing interactions for and presentation of a navigation drawer.
 * See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
 * design guidelines</a> for a complete explanation of the behaviors implemented here.
 */
public class NavigationDrawerFragment extends Fragment {

    /**
     * Remember the position of the selected item.
     */
    private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";

    /**
     * Per the design guidelines, you should show the drawer on launch until the user manually
     * expands it. This shared preference tracks this.
     */
    private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
    private static final String TAG = NavigationDrawerFragment.class.getSimpleName();

    private NavigationDrawerCallbacks mCallbacks;
    private ActionBarDrawerToggle mDrawerToggle;

    private DrawerLayout mDrawerLayout;
    private ExpandableListView mDrawerListView;
    private View mFragmentContainerView;

    private int mCurrentSelectedPosition = 0;
    private boolean mUserLearnedDrawer;


    private List<Category> categories;

    public NavigationDrawerFragment() {
    }

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

    }

    @Override
    public void onActivityCreated (Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Indicate that this fragment would like to influence the set of actions in the action bar.
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        mDrawerListView = (ExpandableListView) inflater.inflate(
                R.layout.fragment_navigation_drawer, container, false);

        setupAdapter();
        setupListeners();

        return mDrawerListView;
    }

    private void setupListeners() {
        mDrawerListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
                Log.d(TAG, "Group clicked: i: " + i + " / l: " + l);

                /**
                 * This method needs to differentiate between groups with and without child elements.
                 *
                 * If the users clicks on a group with child elements the list should expand as expected.
                 * A group without any child elements should act as a normal item in the list.
                 */

                final boolean b = !categories.get(i).hasSub();

                if (b) {
                    showProductList(categories.get(i).getName(), categories.get(i).getProducts());
                }

                return b;
            }
        });

        mDrawerListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int groupPos, int childPos, long l) {
                Log.d(TAG, "Child clicked: groupPos: " + groupPos + " childPos: " + childPos + " / l: " + l);

                showProductList(categories.get(groupPos).getSub(childPos).getName(), categories.get(groupPos).getSub(childPos).getProducts());

                return false;
            }
        });
    }

    /**
     * setupAdapter parses the (dummy) list from the #getData function to create a dynamic
     * list.
     *
     * The modal is fairly simple and only used to demonstrate how everything could look like
     * and work.
     *
     * In this case a list of Categories will be used to create the group items of the ExpandableListView.
     * Every category can have sub categories. Those sub categories will be shown as the child items
     * of the groups. Both categories and sub categories can have products. But only categories without
     * any sub categories will have any.
     *
     * Category group items without any sub categories should act the same way items in a
     * normal list view would.
     */
    private void setupAdapter() {
        categories = getData();

        List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
        List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>();


        for (final Category category: categories) {
            groupData.add(new HashMap<String, String>() {{
                put("ROOT_NAME", category.getName());
            }});

            List<Map<String, String>> child = new ArrayList<Map<String, String>>();

            for (final SubCategory sub : category.subs()) {
                child.add(new HashMap<String, String>() {{
                    put("CHILD_NAME", sub.getName());
                }});
            }

            childData.add(child);
        }

        DrawerExpandableAdapter adapter = new DrawerExpandableAdapter(
                getActivity(),

                groupData,
                R.layout.listelement_group_expanded,
                R.layout.listelement_group,
                R.layout.listelement_group_no_child,
                new String[] { "ROOT_NAME" },
                new int[] { android.R.id.text1 },

                childData,
                R.layout.listelement_child,
                new String[] { "CHILD_NAME" },
                new int[] { android.R.id.text1 }
        );

        mDrawerListView.setAdapter(adapter);
        mDrawerListView.setGroupIndicator(null);
    }

    /**
     * This implementation of getData() only creates dummy data to fill the list with items.
     * In any real application this data could come from anywhere.
     */
    private List<Category> getData() {
        List<Category> list = new ArrayList<Category>();

        Category first = new Category("Meat");
        first.addSub(new SubCategory("Pork", new String[] { "Pork steak", "Pork thing", "pork pork" }));
        first.addSub(new SubCategory("Chicken", new String[] { "chicken 1", "Pice of chicken", "More chicken stuff" }));
        first.addSub(new SubCategory("Fish", new String[] { "Big fish", "Medium fish", "Small fish" }));

        Category second = new Category("Pizza", new String[] { "Pizza 123", "Pizza Margarita", "Pizza Prosciutto" });

        Category third = new Category("Salad");
        third.addSub(new SubCategory("Green Salad", new String[]{"Caesar Salad", "Chef Salad"}));
        third.addSub(new SubCategory("Bound salad", new String[]{"Potato Salad", "Pasta Salad", "Tuna Salad", "Egg Salad", "Chicken Salad"}));
        third.addSub(new SubCategory("Vegetable Salad", new String[] { "Normal Salad", "Something Salad", "Tomato Salad" }));


        list.add(first);
        list.add(second);
        list.add(third);

        return list;
    }

    public boolean isDrawerOpen() {
        return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
    }

    /**
     * Users of this fragment must call this method to set up the navigation drawer interactions.
     *
     * @param fragmentId   The android:id of this fragment in its activity's layout.
     * @param drawerLayout The DrawerLayout containing this fragment's UI.
     */
    public void setUp(int fragmentId, DrawerLayout drawerLayout) {
        mFragmentContainerView = getActivity().findViewById(fragmentId);
        mDrawerLayout = drawerLayout;

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        // set up the drawer's list view with items and click listener

        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the navigation drawer and the action bar app icon.
        mDrawerToggle = new ActionBarDrawerToggle(
                getActivity(),                    /* host Activity */
                mDrawerLayout,                    /* DrawerLayout object */
                R.drawable.ic_drawer,             /* nav drawer image to replace 'Up' caret */
                R.string.navigation_drawer_open,  /* "open drawer" description for accessibility */
                R.string.navigation_drawer_close  /* "close drawer" description for accessibility */
        ) {
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                if (!isAdded()) {
                    return;
                }

                getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                if (!isAdded()) {
                    return;
                }

                if (!mUserLearnedDrawer) {
                    // The user manually opened the drawer; store this flag to prevent auto-showing
                    // the navigation drawer automatically in the future.
                    mUserLearnedDrawer = true;
                    SharedPreferences sp = PreferenceManager
                            .getDefaultSharedPreferences(getActivity());
                    sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
                }

                getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }
        };

        if (!mUserLearnedDrawer) {
            mDrawerLayout.openDrawer(mFragmentContainerView);
        }

        mDrawerLayout.post(new Runnable() {
            @Override
            public void run() {
                mDrawerToggle.syncState();
            }
        });

        mDrawerLayout.setDrawerListener(mDrawerToggle);
    }

    private void showProductList(String name, String[] items) {
        if (mDrawerLayout != null) {
            mDrawerLayout.closeDrawer(mFragmentContainerView);
        }
        if (mCallbacks != null) {
            mCallbacks.showList(name, items);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mCallbacks = (NavigationDrawerCallbacks) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCallbacks = null;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        if (mDrawerLayout != null && isDrawerOpen()) {
            showGlobalContextActionBar();
        }
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void showGlobalContextActionBar() {
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setTitle(R.string.app_name);
    }

    private ActionBar getActionBar() {
        return getActivity().getActionBar();
    }

    public static interface NavigationDrawerCallbacks {
        void showList(String name, String[] items);
    }
}




Java Source Code List

de.frost.david.android.ApplicationTest.java
de.frost.david.android.MyActivity.java
de.frost.david.android.adapters.DrawerExpandableAdapter.java
de.frost.david.android.fragments.ItemListFragmentFragment.java
de.frost.david.android.fragments.NavigationDrawerFragment.java
de.frost.david.android.model.Category.java
de.frost.david.android.model.SubCategory.java