I had a navigation drawer working a while back, but then I decided to update it to use a Toolbar instead of the default support action bar. Now, I have a situation where when I click the hamburger menu, the navigation drawer doesn't open. However, I can slide from left to right and open it. The problem is, it's now empty.
values-v21/styles.xml
<style name="Material" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">#color/app_green</item>
<item name="colorPrimaryDark">#color/app_green_dark</item>
<item name="android:textColorPrimary">#color/action_bar_text</item>
<item name="android:textColor">#color/secondary_text_color</item>
<item name="android:color">#color/secondary_text_color</item>
<item name="android:colorAccent">#color/app_green</item>
<item name="android:editTextColor">#color/secondary_text_color</item>
<item name="textHeaderMaxLines">#integer/text_header_max_lines</item>
<item name="trackAbstractMaxLines">#integer/track_abstract_max_lines</item>
<item name="activatableItemBackground">#drawable/activatable_item_background</item>
<!-- ActionBar Styles -->
<item name="android:windowNoTitle">true</item>
<!--We will be using the toolbar so no need to show ActionBar-->
<item name="android:windowActionBar">false</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">?android:attr/colorPrimaryDark</item>
<!-- Global UI Assignments -->
<item name="android:spinnerStyle">#style/Material.Widget.Spinner</item>
<item name="android:buttonStyle">#style/Material.Widget.Button</item>
<item name="android:checkboxStyle">#style/Material.Widget.Checkbox</item>
<item name="android:textAppearance">#android:style/TextAppearance</item>
<item name="android:popupWindowStyle">#style/Material.Window.Popup</item>
<!-- ViewPager -->
<item name="vpiCirclePageIndicatorStyle">#style/Material.Activity.Login.ViewPagerIndicator.CustomCircle</item>
<item name="buttonBarStyle">?android:buttonBarStyle</item>
<item name="buttonBarButtonStyle">?android:buttonBarButtonStyle</item>
<item name="indeterminateProgressStyle">?android:indeterminateProgressStyle</item>
</style>
navigation_drawer.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!-- The main content view. Must be first child because XML ordering implies stacking
context -->
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">
<!-- Our App Bar. Placed here so we can draw over it with the navigation drawer. -->
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/actionBarSize"
android:background="?android:attr/colorPrimary" />
<!-- Our actual content view. -->
<FrameLayout
android:id="#+id/drawer_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" />
</LinearLayout>
<!-- The navigation drawer itself. -->
<ListView
android:id="#+id/drawer_list"
android:layout_width="300dp"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:layout_gravity="start"
android:background="#android:color/white"
android:fitsSystemWindows="true"
/>
NavigationDrawerActivity.java
public class NavigationDrawerActivity extends ActionBarActivity
implements AdapterView.OnItemClickListener {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private LayoutInflater mInflater;
private NavDrawerItemAdapter mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
// Our "App bar". This will only be populated if the current SDK is >= 21. Otherwise, we'll use an
// action bar that will be populated when the app first starts.
private Toolbar mAppBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_drawer);
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
setupNavigationDrawer();
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Toggles the state of the navigation drawer (i.e. closes it if it's open, and opens it if
* it's closed).
*/
public void toggleNavigationDrawer() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
closeNavigationDrawer();
} else {
openNavigationDrawer();
}
}
/**
* Opens the navigation drawer.
*/
public void openNavigationDrawer() {
mDrawerLayout.openDrawer(GravityCompat.START);
}
/**
* Closes the navigation drawer.
*/
public void closeNavigationDrawer() {
mDrawerLayout.closeDrawer(GravityCompat.START);
}
/**
* Initializes items specific to the navigation drawer.
*/
private void setupNavigationDrawer() {
mDrawerLayout = (DrawerLayout) mInflater.inflate(R.layout.navigation_drawer, null); // "null" is important.
mDrawerLayout.setStatusBarBackgroundColor(getResources().getColor(R.color.app_green));
// We want to use the toolbar if the version is 21 or greater, because is has more flexibility
// than the standard ActionBar
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mAppBar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(mAppBar);
}
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayShowHomeEnabled(false);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* Our context (Activity that hosts this drawer) */
mDrawerLayout, /* The DrawerLayout where the nav drawer will be drawn */
mAppBar, /* The Toolbar that is being used as an app bar. */
R.string.drawer_open, /* Description of "open drawer", for accessibility */
R.string.drawer_close /* Description of "close drawer", for accessibility */
) {
/**
* Called when a drawer has settled in a completely closed state.
*/
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
supportInvalidateOptionsMenu();
}
/**
* Called when a drawer has settled in a completely open state.
*/
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
supportInvalidateOptionsMenu();
}
};
mDrawerList = (ListView) mDrawerLayout.findViewById(R.id.drawer_list);
NavDrawerGroup userToolsGroup = new NavDrawerGroup(R.string.drawer_group_usertools, false, 1);
NavDrawerGroup toolBoxGroup = new NavDrawerGroup(R.string.drawer_group_toolbox, true, 2);
NavDrawerGroup supportGroup = new NavDrawerGroup(R.string.drawer_group_support, true, 3);
NavDrawerItem[] navDrawerItems = {
new NavDrawerItem(R.string.drawer_item_main, R.drawable.ic_main, NavDrawerGroup.DEFAULT_GROUP),
new NavDrawerItem(R.string.drawer_item_tool_one, R.drawable.ic_tool_one, NavDrawerGroup.DEFAULT_GROUP),
new NavDrawerItem(R.string.drawer_item_tool_two, R.drawable.ic_tool_two, userToolsGroup),
};
mAdapter = new NavDrawerItemAdapter(this, navDrawerItems);
mDrawerList.setAdapter(mAdapter);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerList.setOnItemClickListener(this);
}
}
I know the NavDrawerItem stuff looks kinda wonky, but I have verified that it works with the old navigation drawer (pre-Toolbar), and all it is really doing is some logic to populate the ListView items with an icon and place them in an appropriate grouping. So, I am fairly confident that this is not the problem.
Even if it was, I should get something other than the empty white background, because the layout for the nav drawer actually sets a header for the ListView that has a green background, which I am not seeing.
Edit:
As per #blacksh33p's comments below, I removed the code that handled different API levels differently, and changed the mDrawerToggle constructor to:
Hm, no joy. I removed the conditional detecting the API level, and just initialized the Toolbar, and then changed the mDrawerToggle to the following:
mDrawerToggle = new ActionBarDrawerToggle(
this, /* Our context (Activity that hosts this drawer) */
mDrawerLayout, /* The DrawerLayout where the nav drawer will be drawn */
mAppBar, /* The Toolbar that is being used as an app bar. */
R.string.drawer_open, /* Description of "open drawer", for accessibility */
R.string.drawer_close /* Description of "close drawer", for accessibility */
) {
/**
* Called when a drawer has settled in a completely closed state.
*/
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
supportInvalidateOptionsMenu();
}
/**
* Called when a drawer has settled in a completely open state.
*/
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
supportInvalidateOptionsMenu();
}
};
But, I end up with the same result. :(
Remove code from onCreate and add into setContentView
refer this DrawerActivity it may help..!!
public class DrawerActivity extends ActionBarActivity {
protected ActionBarDrawerToggle mDrawerToggle;
private String[] mModulesTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private Intent intent;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.options, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_search:
intent = new Intent(this, JoinLeagueActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.push_left_in,R.anim.push_left_out);
return true;
case R.id.action_add:
intent = new Intent(this, CreateLeagueActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.push_left_in,R.anim.push_left_out);
return true;
case R.id.contactUs:
FragmentManager fm = this.getSupportFragmentManager();
DialogFragment dialog = new ContactUsDialogFragment(); // creating new object
dialog.show(fm, "dialog");
return new ContactUsDialogFragment() != null;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void setContentView(final int layoutResID) {
View fullLayout = (DrawerLayout) getLayoutInflater().inflate(
R.layout.layout_drawer, null);
FrameLayout actContent = (FrameLayout) fullLayout
.findViewById(R.id.content_frame);
mModulesTitles = getResources().getStringArray(R.array.modules_array);
mDrawerLayout = (DrawerLayout) fullLayout
.findViewById(R.id.drawer_layout);
mDrawerList = (ListView) fullLayout.findViewById(R.id.left_drawer);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(mModulesTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(mModulesTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(mModulesTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(mModulesTitles[3], navMenuIcons.getResourceId(3, -1)));
// Pages
navDrawerItems.add(new NavDrawerItem(mModulesTitles[4],-1));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(mModulesTitles[5], -1));
navDrawerItems.add(new NavDrawerItem(mModulesTitles[6], -1));
// Recycle the typed array
navMenuIcons.recycle();
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mModulesTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle(R.string.app_name);
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle(R.string.app_name);
}
};
Log.e("DRAWERLAYOUT###", "" + mDrawerLayout);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
getLayoutInflater().inflate(layoutResID, actContent, true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
super.setContentView(fullLayout);
}
public class DrawerItemClickListener implements
ListView.OnItemClickListener {
public DrawerItemClickListener() {
// TODO Auto-generated constructor stub
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mModulesTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
if (position == 0) {
Intent intent = new Intent(this, DashboardActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
if (position == 1) {
Intent intent = new Intent(this, LeagueActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
if (position == 2) {
Intent intent = new Intent(this, MatchupActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
if (position == 3) {
Intent intent = new Intent(this, HelpActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
if (position == 4) {
Intent intent = new Intent(this, PrivacyActivity.class);
intent.putExtra("from_register", false);
startActivity(intent);
overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
if (position == 5) {
Intent intent = new Intent(this, TermsActivity.class);
intent.putExtra("from_register", false);
startActivity(intent);
overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
if (position == 6) {
SharedPreferenceUtil.putValue("loginStatus", false);
Intent intent = new Intent(this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
this.finish();
overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
}
}
Since you're extending ActionBarActivity, there's no need for you to handle the API levels differently, you are able to use the support Toolbar down to API 7.
I think if you use the other ActionBarDrawerToggle constructor your code will work. Try this:
mDrawerToggle = new ActionBarDrawerToggle(
this, /* Our context (Activity that hosts this drawer) */
mDrawerLayout, /* The DrawerLayout where the nav drawer will be drawn */
R.string.drawer_open, /* Description of "open drawer", for accessibility */
R.string.drawer_close /* Description of "close drawer", for accessibility */
) {
/**
* Called when a drawer has settled in a completely closed state.
*/
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
supportInvalidateOptionsMenu();
}
/**
* Called when a drawer has settled in a completely open state.
*/
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
supportInvalidateOptionsMenu();
}
};
I'm developing an app using drawerLayout with my own Toolbar, and it works so well on my device (android 5.0.1). To do that, I have a xml layout like that:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#F78B1E"
android:minHeight="?attr/actionBarSize" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<!-- The navigation drawer -->
<ListView
android:id="#+id/left_navigation"
android:layout_width="400dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#fff"
/>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
Related
Why is my navigation drawer in android not displaying hamburger icon.
I have done everything as it is supposed to be done by it is still not getting displayed?
public class Main extends ActionBarActivity {
private String[] mPlanetTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private CharSequence mTitle;
private ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maina);
mTitle = "test";
ArrayList<Integer> draw=new ArrayList();
draw.add(R.drawable.elec);draw.add(R.drawable.mob);draw.add(R.drawable.auto);draw.add(R.drawable.pet);draw.add(R.drawable.est);
mPlanetTitles = new String[]{"Electronic ads", "Mobile ads", "Automobile ads","Pets ads","Real Estate ads"};
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
Adapt c=new Adapt(this,draw);
mDrawerList.setAdapter(c);
DisplayMetrics displayMetrics =getApplicationContext().getResources().getDisplayMetrics();
int height=(int)((300 * displayMetrics.density) + 0.5);
GridView g=(GridView)findViewById(R.id.gridview);
ImageAdapter a=new ImageAdapter(this,draw);
g.setAdapter(a);
g.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
startActivity(new Intent(Main.this, MainActivity.class));
}
});
// Set the adapter for the list view
// mDrawerList.setAdapter(new ArrayAdapter<String>(this,
// R.layout.drawer_list_item, mPlanetTitles));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
mDrawerList.setItemChecked(i, true);
//setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
});
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
mDrawerToggle.syncState();
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
mDrawerToggle.syncState();
getSupportActionBar().setTitle(mTitle);
mDrawerList.bringToFront();
invalidateOptionsMenu();
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setIcon(R.drawable.ic_drawer);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
// Sync the toggle state after onRestoreInstanceState has occurred.
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
/**
* Swaps fragments in the main content view
*/
private void selectItem(int position) {
Toast.makeText(this, R.string.app_name, Toast.LENGTH_SHORT).show();
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
}
This is my layout file.
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!-- The main content view -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView
android:id="#+id/gridview"
android:layout_width="match_parent"
android:numColumns="3"
android:gravity="center"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:layout_height="match_parent"/>
</RelativeLayout>
<!-- The navigation drawer -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
/>
</android.support.v4.widget.DrawerLayout>
Why is icon hamburger not showing?
Also remember that, ActionBarActivity is Deprecated use: AppCompatActivity and about NavigationDrawer you should use NavigationView.
It looks like you are using the deprecated version of ActionBarDrawerToggle found in v4 of the support library. Your IDE should be warning you about this usage. You are also using the deprecated ActionBarActivity.
You should switch to the new ActionBarDrawerToggle found in the v7 support library.
Swapping the newer one in is easy- just change your import and remove the R.drawable.ic_drawer parameter. The new toggle provides the drawer drawable for you.
I generated a navigation drawer with a template in Android Studio but i want to know how I can customize the first row of the navigation drawer's ListView to make it look like the one in this example: https://raw.githubusercontent.com/rudsonlive/NavigationDrawer-MaterialDesign/master/Screenshot/Screenshot_01.png
Here is my fragment for the Navigation Drawer :
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";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#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 = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
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().supportInvalidateOptionsMenu(); // 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().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#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);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
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 ((ActionBarActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
Doing The Most Of The Part In The Xml Would be better !!
the for the navigation drawer xml code for the activity
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer"
tools:openDrawer="start"
tools:context=".MainActivity">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/holo_blue_light"
app:title="HOME"
app:titleTextColor="#color/cardview_light_background" />
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_head"
app:menu="#menu/iconmenu"
>
</com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
The Main Solution !!
HERE IN THE NAVIGATION VIEW "APP:MENU=#MENU/ICONMENU"
Has been set to a xml file which contains all the details
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_head"
app:menu="#menu/iconmenu"
>
</com.google.android.material.navigation.NavigationView>
the iconmenu file contains the following xml code
Here Is Where You Can Edit , Add , Remove Contents Which Are Going To Be Displayed On The Navigation Drawer
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/home"
android:title="Home"/>
<item android:id="#+id/account"
android:title="Account"/>
<item android:id="#+id/orders"
android:title="Your Orders"/>
<item android:id="#+id/abt"
android:title="About Us"/>
</menu>
And The Java Code For It To Be Responsive
NavigationView nav;
ActionBarDrawerToggle toggle;
DrawerLayout drawer;
Toolbar tool;
setSupportActionBar(tool);
nav=(NavigationView)findViewById(R.id.nav);
drawer=(DrawerLayout)findViewById(R.id.drawer);
toggle=new ActionBarDrawerToggle(this,drawer,tool,R.string.open,R.string.close);
drawer.addDrawerListener(toggle);
toggle.syncState();
nav.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.home) {
drawer.closeDrawer(GravityCompat.START);
}
else if (item.getItemId() == R.id.account) {
Intent i=new Intent(MainActivity.this,acount.class);
startActivity(i);
}
else if (item.getItemId() == R.id.orders) {
Intent i=new Intent(MainActivity.this,totalOrders.class);
startActivity(i);
}
else if(item.getItemId()==R.id.abt)
{
Intent i=new Intent(MainActivity.this,about.class);
startActivity(i);
}
return true;
}
});
I've been following http://developer.android.com/training/implementing-navigation/nav-drawer.html to set up a navigation drawer in my app. Once an item in the drawer has been selected, the current fragment should be removed and replaced with a new ListFragment. However, both remain and are drawn on top of each other.
mainpage.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/background_light">
<!-- The main content view -->
<RelativeLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/mainListFragment"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:name="com.example.SpeakEasy.MainPageListFragment"
android:layout_alignParentLeft="true"
android:layout_margin="2dp">
</fragment>
</RelativeLayout>
<!-- The navigation drawer -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="150dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:choiceMode="singleChoice"
android:divider="#android:color/darker_gray"
android:dividerHeight="0dp"
android:background="#android:color/background_light">
</ListView>
</android.support.v4.widget.DrawerLayout>
MainPage.java:
public class MainPage extends SherlockFragmentActivity {
public static AmazonClientManager clientManager = null;
protected UiLifecycleHelper uiHelper;
private String[] categoryTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
clientManager = new AmazonClientManager(getSharedPreferences("speakeasySDB", Context.MODE_PRIVATE));
uiHelper = new UiLifecycleHelper(this, null);
uiHelper.onCreate(savedInstanceState);
setTitle("Main Feed");
setContentView(R.layout.mainpage);
categoryTitles = getResources().getStringArray(R.array.navigationDrawerCategories);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(getTitle());
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(getTitle());
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.activity_list_item, android.R.id.text1, categoryTitles));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
/**
* Swaps fragments in the main content view
*/
private void selectItem(int position) {
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragment = null;
// Create a new fragment and specify the planet to show based on position
switch (position) {
case 0:
Toast.makeText(this, "Following not yet implemented", Toast.LENGTH_SHORT).show();
break;
case 1:
fragment = new HomePageListFragment();
fragmentTransaction.replace(R.id.mainListFragment, fragment).commit(); //R.id.content_frame didn't work either
break;
}
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
getSupportActionBar().setTitle(categoryTitles[position] + "Quotes");
mDrawerLayout.closeDrawer(mDrawerList);
}
}
Any ideas what could be happening?
I see that you have fragment declared in the layout file but you are trying to use it in a dynamic way. Replace the fragment with FrameLayout/LinearLayout.
Then you can do transaction.replace(id,fragment,tag).commit();
Hope this helps.
I need your advice. In Google+ App for Android, there are two elements, that I don't know how to put together. One is "Navigation Drawer" and second is "Action Bar Navigation Spinner". Do you know how these two elements put together?
Thank you very much for your advice!
P.S. I know, I'm lame :) (and I apologize for my English)
Add the spinner to the NavigationBar.
The basic procedure to enable drop-down navigation is:
1.Create a SpinnerAdapter that provides the list of selectable items for the drop-down and the layout to use when drawing each item in the list.
2.Implement ActionBar.OnNavigationListener to define the behavior that occurs when the user selects an item from the list.
3.During your activity's onCreate() method, enable the action bar's drop-down list by calling setNavigationMode(NAVIGATION_MODE_LIST).
4.Set the callback for the drop-down list with setListNavigationCallbacks()
http://developer.android.com/guide/topics/ui/actionbar.html
Check the topic Adding Drop-down Navigation
Example:
public class MainActivity extends Activity implements OnNavigationListener
Then
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.planets_array,
android.R.layout.simple_spinner_dropdown_item);
getActionBar().setListNavigationCallbacks(mSpinnerAdapter , this);
Then
#Override
public boolean onNavigationItemSelected(int arg0, long arg1) {
Toast.makeText(getApplicationContext()," text",1000).show();
return true;
}
Snap
Example:
public class MainActivity extends Activity implements ActionBar.OnNavigationListener {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
public ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBar = getActionBar();
SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.planets_array,
android.R.layout.simple_spinner_dropdown_item);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
getActionBar().setListNavigationCallbacks(mSpinnerAdapter,this);
//mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// mDrawerList.setBackgroundColor(Color.WHITE);
// 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
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch(item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
ActionBar actionBar =getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
// setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
//getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PlanetFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
private static WeakReference<MainActivity> mTarget;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(mTarget!=null)
{
MainActivity target = mTarget.get();
ActionBar actionBar = getActivity().getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
//actionBar.setTitle("Fragment");
//target.mDrawerToggle.setDrawerIndicatorEnabled(false);
}
else
{
Log.i("............","Null");
}
}
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mTarget = new WeakReference<MainActivity>( (MainActivity) getActivity());
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources().getStringArray(R.array.planets_array)[i];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
// getActivity().setTitle(planet);
return rootView;
}
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "text", Toast.LENGTH_LONG).show();
return true;
}
}
activity_main.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
The drawer is given a fixed width in dp and extends the full height of
the container. A solid background is used for contrast
with the content view. -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
/>
</android.support.v4.widget.DrawerLayout>
drawe_list_item.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
android:background="#drawable/selector"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:textColor="#fff"
android:minHeight="?android:attr/listPreferredItemHeightSmall"/>
fragment_planet.xml
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:gravity="center"
android:padding="32dp" />
Look these link. may be help you this?
Here is the code examples of Navigation Drawer, and the sample app:
sample app
How to add spinner to subtitle as in the Play Music app for Android?
I am sorry for my english I am using navigation drawer and I want that navigation drawer will be behind the layout like in facebook. Here is the code, More specifically I want drawer listview be under framelayout. Any help please. Thanks.
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// 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
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch(item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PlanetFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources().getStringArray(R.array.planets_array)[i];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}
}
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
The drawer is given a fixed width in dp and extends the full height of
the container. A solid background is used for contrast
with the content view. -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
Use ContentDisplaceDrawerToggle from my Library, if you want to combine with ActionBarDrawerToggle, you might want to use the wrapper provided in the library.
mAllToggles = new ActionBarDrawerToggleWrapper(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close);
mAllToggles.addPartnerToggle(new ContentDisplaceDrawerToggle(this, mDrawerLayout, R.id.content_frame));
mAllToggles.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mAllToggles);
Adding shadow (along the left margin) to your content view instead to the Drawer will make your Drawer look like it is behind the content view.