Friday, September 12, 2014

Adding Navigation Drawer to Android Project

When attempting to add a navigation drawer to my application, I found that the templates used by Android Studio caused a crash. I am not sure what caused this crash, but I got very tired of attempting to debug boilerplate code. Instead, I followed the "Creating a Navigation Drawer" Tutorial on HMKCode (http://hmkcode.com/android-creating-a-navigation-drawer/), I found this tutorial to be the most helpful one available. And the result actually worked.

What this tutorial missed, I found in the "Navigation Drawer Android Example" (http://javatechig.com/android/navigation-drawer-android-example#33-handle-navigation-click-events).  


1) The ability to load a fragment:

// Creating a fragment object
WebViewFragment rFragment = new WebViewFragment();

// Passing selected item information to fragment
Bundle data = new Bundle();
data.putInt("position", position);
data.putString("url", getUrl(position));
rFragment.setArguments(data);

// Getting reference to the FragmentManager
FragmentManager fragmentManager = getFragmentManager();

// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();

// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, rFragment);

// Committing the transaction
ft.commit();


2) The ability to change text when the drawer is opened and closed

mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {

/** Called when drawer is closed */
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}

/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle("JAVATECHIG.COM");
invalidateOptionsMenu();
}

};