I am aware that this question exists but the answers don't work for my case.
I have a navigation drawer with four items, but when I click on the first one (the one i'm working on right now), the new activity I created doesn't open, I have looked and tried everything I found on the internet but nothing seems to work.
i'm kinda new to android studio so I really don't know how to fix this. The android studio version I am using is 3.0.
This is my menu xml:
<?xml version="1.0" encoding="utf-8"?>
<!--Icons made by http://www.freepik.com
from "https://www.flaticon.com
is licensed by http://creativecommons.org/licenses/by/3.0/-->
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/m1" android:title="Agora Mall"
android:icon="#drawable/ic_ammunition"/>
<item android:id="#+id/m2" android:title="Downtown Center"
android:icon="#drawable/ic_ammunition"/>
<item android:id="#+id/m3" android:title="Galeria 360"
android:icon="#drawable/ic_ammunition"/>
<item android:id="#+id/m4" android:title="Sambil"
android:icon="#drawable/ic_ammunition"/>
</menu>
this is the main activity class code:
package com.example.arlet.storemaps;
import android.content.Intent;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.Window;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)) {
return true;
}
switch(item.getItemId()){
case R.id.m1:
Intent intent = new Intent(MainActivity.this, AgoraActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
You must implement onNavigationItemSelected() for the navigation drawer menu.
onOptionsItemSelected() is related to the toolbar options menu items.
You can find all the necessary code for this if you create a new project and choose
Navigation Drawer Activity
as the type of your MainActivity.
You Can handle navigation drawer item click in following way:
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.m1:
Intent intent = new Intent(MainActivity.this, AgoraActivity.class);
startActivity(intent);
return true;
break;
case R.id.m2:
break;
case R.id.m3:
break;
case R.id.m4:
break;
}
menuItem.setChecked(true);
return true;
}
});
You must implement NavigationView.OnNavigationItemSelectedListener for the drawer items to work perfectly
Add this to your class declaration
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
// then overide this method to
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id){
case R.id.m1:
Intent intent = new Intent(MainActivity.this, AgoraActivity.class);
startActivity(intent);
return true;
//other cases goes here
}
return super.onOptionsItemSelected(item);
}
//you might want to ovewrite this method too
#Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
Related
Hey Guys I read this thread a while ago and tried to replicate it since i'm using multiple activities within my app.
I copied all my code for the navigation drawer within my new NavigationDrawerActivity.java which looks like this:
package info.androidhive.navigationdrawer.activity;
import android.content.Intent;
import android.os.Handler;
import android.support.annotation.LayoutRes;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import info.androidhive.navigationdrawer.R;
import info.androidhive.navigationdrawer.fragment.CameraFragment;
import info.androidhive.navigationdrawer.fragment.ExposeDetailFragment;
import info.androidhive.navigationdrawer.fragment.HomeFragment;
import info.androidhive.navigationdrawer.fragment.MyAccountFragment;
import info.androidhive.navigationdrawer.fragment.SettingsFragment;
public class NavigationDrawerActivity extends AppCompatActivity {
public DrawerLayout drawerLayout;
public NavigationView navigationView;
public DrawerLayout drawer;
public View navHeader;
public TextView txtName;
public TextView txtWebsite;
public Toolbar toolbar;
// index to identify current nav menu item
public static int navItemIndex = 0;
// tags used to attach the fragments
public static final String TAG_HOME = "home";
public static final String TAG_CAMERA = "camera";
public static final String TAG_MOVIES = "movies";
public static final String TAG_MY_ACCOUNT = "myaccoount";
public static final String TAG_SETTINGS = "settings";
public static String CURRENT_TAG = TAG_HOME;
// toolbar titles respected to selected nav menu item
public String[] activityTitles;
// flag to load home fragment when user presses back key
public boolean shouldLoadHomeFragOnBackPress = true;
public Handler mHandler;
#Override
public void setContentView(#LayoutRes int layoutResID) {
drawerLayout = (DrawerLayout) getLayoutInflater().inflate(R.layout.activity_navigation_drawer,null);
getLayoutInflater().inflate(layoutResID,drawerLayout,true);
super.setContentView(drawerLayout);
//DrawerContent here
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mHandler = new Handler();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
// Navigation view header
navHeader = navigationView.getHeaderView(0);
txtName = (TextView) navHeader.findViewById(R.id.name);
txtWebsite = (TextView) navHeader.findViewById(R.id.webseite);
// load toolbar titles from string resources
activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);
// load nav menu header data
loadNavHeader();
// initializing navigation menu
setUpNavigationView();
}
/***
* Load navigation menu header information
* like background image, profile image
* name, website, notifications action view (dot)
*/
private void loadNavHeader() {
// name, website
txtName.setText("Ravi Tamada");
txtWebsite.setText("www.androidhive.info");
}
/***
* Returns respected fragment that user
* selected from navigation menu
*/
public void loadHomeFragment() {
// selecting appropriate nav menu item
selectNavMenu();
// set toolbar title
setToolbarTitle();
// if user select the current navigation menu again, don't do anything
// just close the navigation drawer
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawer.closeDrawers();
return;
}
// Sometimes, when fragment has huge data, screen seems hanging
// when switching between navigation menus
// So using runnable, the fragment is loaded with cross fade effect
// This effect can be seen in GMail app
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the main content by replacing fragments
Fragment fragment = getHomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commitAllowingStateLoss();
}
};
// If mPendingRunnable is not null, then add to the message queue
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
}
/*FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Click action
Intent intent = new Intent(NavigationDrawerActivity.this, NewExposeActivity.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Ein neues Exposé erstellen", Toast.LENGTH_LONG).show();
}
});*/
//Closing drawer on item click
drawer.closeDrawers();
// refresh toolbar menu
invalidateOptionsMenu();
}
public Fragment getHomeFragment() {
switch (navItemIndex) {
case 0:
// home
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
case 1:
// expose List
HomeFragment homeFragment1 = new HomeFragment();
return homeFragment1;
case 2:
//Camera fragment
CameraFragment cameraFragment = new CameraFragment();
return cameraFragment;
case 3:
// notifications fragment
MyAccountFragment myAccountFragment = new MyAccountFragment();
return myAccountFragment;
case 4:
// settings fragment
SettingsFragment settingsFragment = new SettingsFragment();
return settingsFragment;
default:
return new HomeFragment();
}
}
public void setToolbarTitle() {
getSupportActionBar().setTitle(activityTitles[navItemIndex]);
}
public void selectNavMenu() {
navigationView.getMenu().getItem(navItemIndex).setChecked(true);
}
public void setUpNavigationView() {
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.home:
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
break;
case R.id.nav_camera:
navItemIndex = 1;
CURRENT_TAG = TAG_CAMERA;
break;
case R.id.nav_movies:
navItemIndex = 2;
CURRENT_TAG = TAG_MOVIES;
break;
case R.id.nav_my_account:
navItemIndex = 3;
CURRENT_TAG = TAG_MY_ACCOUNT;
break;
case R.id.nav_settings:
navItemIndex = 4;
CURRENT_TAG = TAG_SETTINGS;
break;
case R.id.nav_rss:
startActivity( new Intent(NavigationDrawerActivity.this, RSSFeedActivity.class));
drawer.closeDrawers();
return true;
case R.id.nav_login:
startActivity( new Intent(NavigationDrawerActivity.this, LoginActivity.class));
drawer.closeDrawers();
return true;
default:
navItemIndex = 0;
}
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) {
menuItem.setChecked(false);
} else {
menuItem.setChecked(true);
}
menuItem.setChecked(true);
loadHomeFragment();
return true;
}
});
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawer.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessary or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawers();
return;
}
// This code loads home fragment when back key is pressed
// when user is in other fragment than home
if (shouldLoadHomeFragOnBackPress) {
// checking if user is on other navigation menu
// rather than home
if (navItemIndex != 0) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
return;
}
}
super.onBackPressed();
}
#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
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.add_expose) {
Toast.makeText(getApplicationContext(), "Ein neues Exposé soll erstellt werden!", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
and here the activity_navigation_drawer.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" >
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
here is the activity_navigation_drawer.xml which is menu Ressource file:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_home_black_24dp"
android:title="#string/nav_home" />
<item
android:id="#+id/nav_camera"
android:icon="#mipmap/ic_list_black_24dp"
android:title="#string/nav_photos" />
<item
android:id="#+id/nav_movies"
android:icon="#mipmap/ic_camera_alt_black_24dp"
android:title="#string/nav_movies" />
<item
android:id="#+id/nav_my_account"
android:icon="#mipmap/ic_person_black_24dp"
android:title="Mein Account" />
<item
android:id="#+id/nav_settings"
android:icon="#mipmap/ic_settings_black_24dp"
android:title="#string/nav_settings" />
</group>
<item android:title="Other">
<menu>
<item
android:id="#+id/nav_rss"
android:title="News"
android:icon="#mipmap/ic_rss_feed_black_24dp" />
<item
android:id="#+id/nav_login"
android:title="#string/action_logout"
android:icon="#mipmap/ic_lock_black_24dp" />
</menu>
</item>
</menu>
It's working great up to the fact that when i click an item in the navigation nothing happens. Are there any suggestions to what I'm doing wrong.
You can find the whole project here.
Thanks for your help.
First , post a reference or code to how you are creating the menu item , do u create it in the resources menu file or simply load an array , If you are using array then i would suggest you to use menu xml to create menu items.
Something like this:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/new_game"
android:icon="#drawable/ic_new_game"
android:title="#string/new_game"
android:showAsAction="ifRoom"/>
<item android:id="#+id/help"
android:icon="#drawable/ic_help"
android:title="#string/help" />
</menu>
also make corresponding changes in ur code,check
https://developer.android.com/guide/topics/ui/menus.html
https://developer.android.com/training/implementing-navigation/nav-drawer.html
Hi i have this problem with my navigation drawer. The drawer opens fine but i am having problems with the onClickListener. if an item on the drawer is clicked on it doesnt show the related layout instaed a black page shows. Please help
home.java
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.Toast;
public class home extends AppCompatActivity {
//Defining Variables
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Initializing Toolbar and setting it as the actionbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing NavigationView
navigationView = (NavigationView) findViewById(R.id.navigation_view);
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if(menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()){
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.dashboard:
Toast.makeText(getApplicationContext(),"dashboard",Toast.LENGTH_SHORT).show();
Dashboard fragment = new Dashboard();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame,fragment);
fragmentTransaction.commit();
break;
// For rest of the options we just show a toast on click
case R.id.profile:
Toast.makeText(getApplicationContext(),"profile",Toast.LENGTH_SHORT).show();
new Profile();
break;
case R.id.logs:
Toast.makeText(getApplicationContext(),"logs",Toast.LENGTH_SHORT).show();
new Logs();
break;
case R.id.statements:
Toast.makeText(getApplicationContext(),"statements",Toast.LENGTH_SHORT).show();
new Statements();
break;
case R.id.timeline:
Toast.makeText(getApplicationContext(),"timeliine",Toast.LENGTH_SHORT).show();
new Timeline();
break;
case R.id.settings:
Toast.makeText(getApplicationContext(),"settings",Toast.LENGTH_SHORT).show();
new Settings();
break;
default:
Toast.makeText(getApplicationContext(),"Somethings Wrong",Toast.LENGTH_SHORT).show();
break;
}
return true; }
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.openDrawer, R.string.closeDrawer){
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessay or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You're not switching fragments correctly in your case statements. You're only instantiating a new Fragment class and not doing anything with it. You need to do something like this:
Fragment fragment;
switch (menuItem.getItemId()){
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.dashboard:
Toast.makeText(getApplicationContext(),"dashboard",Toast.LENGTH_SHORT).show();
fragment = new Dashboard();
break;
// For rest of the options we just show a toast on click
case R.id.profile:
Toast.makeText(getApplicationContext(),"profile",Toast.LENGTH_SHORT).show();
fragment = new Profile();
break;
case R.id.logs:
Toast.makeText(getApplicationContext(),"logs",Toast.LENGTH_SHORT).show();
fragment = new Logs();
break;
case R.id.statements:
Toast.makeText(getApplicationContext(),"statements",Toast.LENGTH_SHORT).show();
fragment = new Statements();
break;
case R.id.timeline:
Toast.makeText(getApplicationContext(),"timeliine",Toast.LENGTH_SHORT).show();
fragment = new Timeline();
break;
case R.id.settings:
Toast.makeText(getApplicationContext(),"settings",Toast.LENGTH_SHORT).show();
fragment = new Settings();
break;
default:
Toast.makeText(getApplicationContext(),"Somethings Wrong",Toast.LENGTH_SHORT).show();
break;
}
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame,fragment);
fragmentTransaction.commit();
This way you're instantiating a fragment with a proper Fragment class each time, and at the end, replacing the frame with that particular fragment.
Digresion: It is recommended that you use newInstance to get the fragments and not the constructor. This is known as the Singleton design pattern.
about : I just click the menu SideMenu
"Rate" or even other menu, and I want to change the main view that the right arrow shows, but how? and here is the source of github
case 0:
// int the case, click the menu : Rate (or even other menu)
/**
* If I click the menu in the picture : Rate
* I want to change the main layout that the right arrow shows
* but how ?
* 1: what to do with the content view ?
* 2: or what to with the following code ?
*/
break;
You seem to have 2 options:
Intent to a new Activity which has your required functionality
Intent rateIntent = new Intent(CurrentActivity.this, NextActivity.class));
startActivity(rateIntent);
If you use fragments, you will need to replace your current fragment, you can use the FragmentManager for this type of app navigation
NextFragment nextFrag= new NextFragment();
this.getFragmentManager().beginTransaction()
.replace(R.id.Layout_container, nextFrag,TAG_FRAGMENT)
.addToBackStack(null)
.commit();
https://developer.android.com/reference/android/app/FragmentManager.html
https://developer.android.com/reference/android/content/Intent.html
Hope this helps
MainActivity xml
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="fill_parent">
</FrameLayout>
<!-- The navigation drawer -->
<ListView
android:id="#+id/navdrawer"
android:layout_width="#dimen/navdrawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/white"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:drawSelectorOnTop="false">
</ListView>
</android.support.v4.widget.DrawerLayout>
We add fragment in framelayout when click on listview item.
Create fragments
StopAnimationFragment
StartAnimationFragment
ChangeColorFragment
GitHubPageFragment
ShareFragment
RateFragment
package com.ikimuhendis.ldrawer.sample;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.ikimuhendis.ldrawer.ActionBarDrawerToggle;
import com.ikimuhendis.ldrawer.DrawerArrowDrawable;
public class SampleActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerArrowDrawable drawerArrow;
private boolean drawerArrowColor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
ActionBar ab = getActionBar();
ab.setDisplayHomeAsUpEnabled(true);
ab.setHomeButtonEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.navdrawer);
drawerArrow = new DrawerArrowDrawable(this) {
#Override
public boolean isLayoutRtl() {
return false;
}
};
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
drawerArrow, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
String[] values = new String[]{
"Stop Animation (Back icon)",
"Stop Animation (Home icon)",
"Start Animation",
"Change Color",
"GitHub Page",
"Share",
"Rate"
};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position) {
case 0:
mDrawerToggle.setAnimateEnabled(false);
drawerArrow.setProgress(1f);
//create Fragment and call this method
setNavigationFragments(new StopAnimationFragment());
break;
case 1:
mDrawerToggle.setAnimateEnabled(false);
drawerArrow.setProgress(0f);
//create Fragment and call this method
setNavigationFragments(new StopAnimationFragment());
break;
case 2:
mDrawerToggle.setAnimateEnabled(true);
mDrawerToggle.syncState();
//create Fragment and call this method
setNavigationFragments(new StartAnimationFragment());
break;
case 3:
if (drawerArrowColor) {
drawerArrowColor = false;
drawerArrow.setColor(R.color.ldrawer_color);
} else {
drawerArrowColor = true;
drawerArrow.setColor(R.color.drawer_arrow_second_color);
}
mDrawerToggle.syncState();
//create Fragment and call this method
setNavigationFragments(new ChangeColorFragment());
break;
case 4:
//create Fragment and call this method
setNavigationFragments(new GitHubPageFragment());
break;
case 5:
//create Fragment and call this method
setNavigationFragments(new ShareFragment());
break;
case 6:
//create Fragment and call this method
setNavigationFragments(new RateFragment());
break;
}
}
});
}
private void setNavigationFragments(Fragment fragment) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container,fragment).commit();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
Hello i am new to android. I would like to implement navigation drawer consisting of a list of items, which when clicked opens a new activity. Basically a navigation drawer across all the activities. When I select an item from the navigation drawer that particular activity opens but the icon for the navigation drawer (hamburger icon) disappears. How do I get that?
NavBaseActivity.java
package app.pal.study.samplestudy;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.FrameLayout;
public class NavBaseActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_base);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
// getActionBar().setDisplayHomeAsUpEnabled(true);
//getActionBar().setHomeButtonEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.nav_base, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
/* if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);*/
switch (item.getItemId()) {
case android.R.id.home:
drawer.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.item_home) {
// Handle the camera action
startActivity(new Intent(this, Home.class));
} else if (id == R.id.item_syllabus) {
startActivity(new Intent(this, Syllabus.class));
} else if (id == R.id.item_study_time) {
startActivity(new Intent(this, StudyTime.class));
} else if (id == R.id.item_exam) {
startActivity(new Intent(this, Exam.class));
} else if (id == R.id.item_calendar) {
startActivity(new Intent(this, Calendar.class));
} else if (id == R.id.nav_scribble) {
startActivity(new Intent(this, Scribble.class));
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
// `onPostCreate` called when activity start-up is complete after `onStart()`
// NOTE! Make sure to override the method with only a single `Bundle` argument
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
}
}
Syllabus.java
package app.pal.study.samplestudy;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
public class Syllabus extends NavBaseActivity implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_syllabus);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
activity_nav_base.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_nav_base"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_nav_base"
app:menu="#menu/activity_nav_base_drawer" />
</android.support.v4.widget.DrawerLayout>
It is advised to use Navigation Drawer with fragments as it will maintain the nav drawer. You have to convert your activities in fragments. Please check developer link- http://developer.android.com/training/implementing-navigation/nav-drawer.html
Has anyone figured out how to get this method of one main activity pushing in fragments to work with the back button ?
Everything works fine going "forward", and all the fragments get pulled into the content frame, but as soon as you hit the back button, the application closes...most likely because it is the only activity running and the back button closes the activity.
Anyway to put code in to get the fragment manager to go back to the last fragment and not close the activity on the back button ?
I read this post :
I try to do it but i have trouble in the "Navigating between Menu Items" section.
Where do the code of this section go ? In the MainActivity.java file or else?
When i paste it on my IDE (Android Studio 1.4) the items "nvDrawer" and "NavigationView" are red:
Also, i have two onCreate() on the same file.
Can you give me some suggestions how to make it work?
Below the code of my MainActivity.java.
package com.ther01s.android.ma0;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawer;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set a Toolbar to replace the ActionBar.
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Find our drawer view
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
switch (item.getItemId()) {
case android.R.id.home:
mDrawer.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
// Make sure this is the method with just `Bundle` as the signature
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// Find our drawer view
nvDrawer = (NavigationView) findViewById(R.id.nvView);
// Setup drawer view
setupDrawerContent(nvDrawer);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the planet to show based on
// position
Fragment fragment = null;
Class fragmentClass;
switch(menuItem.getItemId()) {
case R.id.nav_first_fragment:
fragmentClass = FirstFragment.class;
break;
default:
fragmentClass = FirstFragment.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
// Highlight the selected item, update the title, and close the drawer
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawer.closeDrawers();
}
}
Install latest android studio . then go to File --> New Project-->Configure your Project-->Target Device-->Choose Navigation Drawer Activity--> finish. You will get an awesome template from Android studio itself. Dont be confused by looking up for other useless tutorials.