This question already has answers here:
NavigationView OnNavigationItemSelectedListener not being called
(3 answers)
Closed 4 years ago.
Nothing happens when i click the items from my navigation drawer. I've tried putting the block of code to replace fragments in the onCreate() method just to test if my FragmentTransaction is working and they work well. I don't know what i am doing wrong. Here's my code for the navigation drawer that i learned from tutorials
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout mDrawerLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setHomeAsUpIndicator(R.drawable.ic_menu);
mDrawerLayout = findViewById(R.id.drawer_layout);
mDrawerLayout.addDrawerListener(
new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(#NonNull View drawerView, float slideOffset) {
}
#Override
public void onDrawerOpened(#NonNull View drawerView) {
}
#Override
public void onDrawerClosed(#NonNull View drawerView) {
}
#Override
public void onDrawerStateChanged(int newState) {
}
}
);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, mDrawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mDrawerLayout.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView)findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
item.setChecked(true);
mDrawerLayout.closeDrawers();
int id = item.getItemId();
FragmentTransaction ft = getFragmentManager().beginTransaction();
switch (id) {
case R.id.nav_budget:
BudgetMain fragBudgetMain = new BudgetMain();
ft.replace(R.id.flContent, fragBudgetMain);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
break;
case R.id.nav_expenses:
Expenses fragExp = new Expenses();
ft.replace(R.id.flContent, fragExp);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
break;
case R.id.nav_selfassessment:
SelfAssessment fragSelf = new SelfAssessment();
ft.replace(R.id.flContent, fragSelf);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
break;
case R.id.nav_mealcard:
MealCard fragMeal = new MealCard();
ft.replace(R.id.flContent, fragMeal);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
break;
case R.id.nav_ranking:
Ranking fragRanking = new Ranking();
ft.replace(R.id.flContent, fragRanking);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
break;
}
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
}
This is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Use DrawerLayout as root container for activity -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:background="#drawable/gradient2">
<!-- Layout to contain contents of main body of screen (drawer will slide over this) -->
<!-- Container for contents of drawer - use NavigationView to make configuration easier -->
<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:menu="#menu/drawer_view"
app:headerLayout="#layout/nav_header"/>
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.DrawerLayout>
This is my app_bar_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
tools:context="com.example.activity.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:background="#drawable/gradient"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?android:attr/actionBarSize"/>
</android.support.design.widget.CoordinatorLayout>
My drawer_view.xml
<?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"
android:title="Home"/>
<item
android:id="#+id/nav_budget"
android:icon="#drawable/ic_budget"
android:title="Budget"/>
<item
android:id="#+id/nav_expenses"
android:icon="#drawable/ic_expenses"
android:title="Expenses"/>
<item
android:id="#+id/nav_mealcard"
android:icon="#drawable/ic_mealcard"
android:title="Meal Card"/>
<item
android:id="#+id/nav_selfassessment"
android:icon="#drawable/ic_selfassessment"
android:title="Self-Assessment"/>
<item
android:id="#+id/nav_ranking"
android:icon="#drawable/ic_ranking"
android:title="Ranking"/>
</group>
</menu>
Try this one please:
mDrawerList.bringToFront();
mDrawerLayout.requestLayout();
So you onCreate() method will look like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setHomeAsUpIndicator(R.drawable.ic_menu);
mDrawerLayout = findViewById(R.id.drawer_layout);
mDrawerLayout.addDrawerListener(
new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(#NonNull View drawerView, float slideOffset) {
}
#Override
public void onDrawerOpened(#NonNull View drawerView) {
}
#Override
public void onDrawerClosed(#NonNull View drawerView) {
}
#Override
public void onDrawerStateChanged(int newState) {
}
}
);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, mDrawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mDrawerLayout.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView)findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
mDrawerList.bringToFront();
mDrawerLayout.requestLayout();
}
My base activity displays the toolbar but has no title, burger or overflow menus on the bar. I can not figure out how to get the menus to show. Any help would be much appreciated! onCreateOptionsMenu() is not being called in the base activity when I debug.
BaseActivity
public abstract class BaseActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView)
findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void setContentView(int layoutResID) {
final DrawerLayout fullView = (DrawerLayout)
getLayoutInflater().inflate(R.layout.activity_base, null);
FrameLayout activityContainer = (FrameLayout)
fullView.findViewById(R.id.activity_content);
getLayoutInflater().inflate(layoutResID, activityContainer, true);
super.setContentView(fullView);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
}
myActivity
public class myActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_item);
}
}
Any idea what I am missing to make this work? I have read around and am really struggling to fix this!
My app_bar_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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"
tools:context="com.mpd.sfs.BaseActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
I have several activities where I want to use the same navigation drawer. Here's part of my Activity class code related to the drawer:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
I'm planning to make a DrawerActivity class and extend it from all those activities which want the Navigation drawer. Therefore, I will have to move all the drawer code to that DrawerActivity.
The problem:
toolbar is important for the initialization of ActionBarDrawerToggle. Every activity has a different toolbar depending upon the needs of that activity. Therefore, the toolbar layouts must be kept in their respective layout xml files. How would I use the toolbar then in the DrawerActivity class?
Layout xml for the drawer:
<?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">
<FrameLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="#+id/frame_layout"
xmlns:android="http://schemas.android.com/apk/res/android">
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
app:itemBackground="#drawable/drawer_list_selector"
style="#style/NavigationDrawer"
app:headerLayout="#layout/sidenav_header"
app:menu="#menu/side_navigation_menu"
app:theme="#style/Drawer"/>
</android.support.v4.widget.DrawerLayout>
Here's the SideNavigation activity (which I'm trying to extend by those classes who need navigation drawer): pastebin.com/hheMXku5
main statement of the log says:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayShowTitleEnabled(boolean)' on a null object reference
Here's the link to the onCreate of one of the activity class that extends the SideNavigation class: pastebin.com/iKYXVbda
okey so as you want to use drawer with Activity. I am posting my code here. I hope this will help you out.
First of all you need to develop NavigationDrawer. I know you can do it by your self.
Now create child Activity for Example Home.java and extend it with your drawer Activity let's say MainActivity.java.
it will be something like this.
public class Home extends MainActivity{
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
Now usually we perform setContentView in onCreate, bur here do something like this.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.home, frameLayout);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
Where frameLayout would be your container, which you have take in MainActivity.
Note : don't forget to take another ToolBar in home Activity. because it will override MainActivity's toolbar.
EDIT
I am posting my Whole code please refer it. Although I have took my custom Navigation drawer but it can work with NavigationView too.
activity_main
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true" >
<RelativeLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="false" >
<!-- ToolBar of MainActivity -->
<include
android:id="#+id/toolbar_headers"
layout="#layout/toolbar_header" />
</RelativeLayout>
<!-- here will be your NavigationView -->
<com.random.extraclasses.ScrimInsetsFrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:layout_marginRight="-8dp"
android:elevation="8dp"
android:fitsSystemWindows="true"
app:insetForeground="#4000" >
<include
android:id="#+id/drawar_layout"
layout="#layout/drawar_layout" />
</com.gujarat.property.extraclasses.ScrimInsetsFrameLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity implements OnClickListener {
protected RelativeLayout frameLayout;
protected DrawerLayout mDrawerLayout;
protected ListView mDrawerList;
protected ScrimInsetsFrameLayout mLayout;
protected ActionBarDrawerToggle mDrawerToggle;
protected static boolean isLaunch = true;
Toolbar toolbar;
private CharSequence mTitle;
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
frameLayout = (RelativeLayout) findViewById(R.id.frame_container);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list);
mLayout = (ScrimInsetsFrameLayout) findViewById(R.id.container);
toolbar = (Toolbar) findViewById(R.id.toolbar_headers);
setSupportActionBar(toolbar);
navDrawerItems = new ArrayList<NavDrawerItem>();
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons
.getResourceId(0, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons
.getResourceId(1, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons
.getResourceId(2, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
.getResourceId(3, -1)));
navMenuIcons.recycle();
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
selectedPos = position - 1;
displayView(position);
}
});
mDrawerList.setAdapter(adapter);
mDrawerList.setFocusable(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name) {
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (isLaunch) {
isLaunch = false;
displayView(0);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void displayView(int position) {
mDrawerLayout.closeDrawer(mLayout);
MainActivity.position = position;
switch (position) {
case 0:
if (this.getClass().getSimpleName().equals("Home")) {
} else {
Intent i = new Intent(this, Home.class);
startActivity(i);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
}
break;
case 1:
if (this.getClass().getSimpleName().equals("ForSale")) {
} else {
Intent i = new Intent(this, ForSale.class);
startActivity(i);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
}
break;
case 2:
if (this.getClass().getSimpleName().equals("ForRent")) {
} else {
Intent i = new Intent(this, ForRent.class);
startActivity(i);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
}
break;
case 3:
if (this.getClass().getSimpleName().equals("NewProjects")) {
} else {
Intent i = new Intent(this, NewProjects.class);
startActivity(i);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
}
break;
default:
break;
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#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 void onClick(View v) {
}
}
And finally Home.java
public class Home extends MainActivity implements OnClickListener {
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.home, frameLayout);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle("");
}
#Override
public void onBackPressed() {
super.onBackPressed();
if (mDrawerLayout.isDrawerOpen(mLayout)) {
isLaunch = false;
mDrawerLayout.closeDrawer(mLayout);
} else {
finishAffinity();
}
}
And just for reference home.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar"
android:background="#drawable/back51" >
<TextView
android:id="#+id/etSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:background="#android:color/transparent"
android:text="Search Property"
android:textColor="#666666" />
</RelativeLayout>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_scrollFlags="scroll|enterAlways"
android:background="#color/toobar"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" >
</android.support.v7.widget.Toolbar>
</RelativeLayout>
I hope this will help you out.
My code throws a NullPointException on the following three lines
drawer.setDrawerListener(toggle)
navigationView.setNavigationItemSelectedListener(this)
drawer.isDrawerOpen(GravityCompat.START
Here is my full activity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
NavigationView navigationView = null;
Toolbar toolbar = null;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
HomeFragment fragment = new HomeFragment();
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
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) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
I followed various answers to try to fix them none of them worked please help.
MainActivity.Xml
<?xml version="1.0" encoding="utf-8"?>
<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" />
Tried adding the onDrawerOpened and onDrawerClosed.
and also the FrameLayout in the app_bar_main also Reports Empty Tag
try putting variables here and add method onDrawerOpened, onDrawerClosed
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
NavigationView navigationView = null;
Toolbar toolbar = null;
DrawerLayout drawer;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
HomeFragment fragment = new HomeFragment();
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
}
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
I'm looking for a way to display the hamburger icon whitout using the Drawer/DrawerToggle and use the default icon included in Android
By setting getSupportActionBar().setDisplayHomeAsUpEnabled(true); it display the back arrow but not the hambuerger. Other post on Stackoverflow (like this or this) use the DrawerLayout or a custom drawable. I cannot find the vector or png for the hamburger icon on the Android source.
Do you know how can I find the original hamburger icon in android/support library? (or how to displayed it)
Note: Vector and png can be found on google.com/design website : http://www.google.com/design/spec/resources/sticker-sheets-icons.html#
In my activity
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(LOG_TAG, "navigation clicked");
}
});
Layout file
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:theme="#style/ThemeOverlay.AppCompat.ActionBar"/>
Styles.xml
<!-- Base application theme. -->
<style name="Theme.AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">#color/primaryDef</item>
<item name="colorPrimaryDark">#color/primaryDarkDef</item>
<item name="colorAccent">#color/primaryDef</item>
<!-- Remove the actionbar shadow-->
<item name="android:windowContentOverlay">#null</item>
</style>
If you want to use the same drawer as lollipop then let me tell you that's not a static image. That image is drawn in real time by a class called DrawerArrowDrawableToggle. So there is no "hamburger" icon for that.
However if you want the hamburger icon with no animation you can find it here:
https://material.io/tools/icons/?icon=menu&style=baseline
To have an animated hamburger icon you should use DrawerLayout with ActionBarDrawerToggle and enable the icon for the ActionBar and for the ActionBarDrawerToggle.
Example:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle mDrawerToggle;
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null)
{
actionBar.setDisplayHomeAsUpEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.hello_world, R.string.hello_world)
{
public void onDrawerClosed(View view)
{
supportInvalidateOptionsMenu();
//drawerOpened = false;
}
public void onDrawerOpened(View drawerView)
{
supportInvalidateOptionsMenu();
//drawerOpened = true;
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
drawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
Also, you need to add these methods to your Activity:
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
For that you just need write to some lines
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.addDrawerListener(toggle);
toggle.setDrawerIndicatorEnabled(true);
toggle.syncState();
toggle.setDrawerIndicatorEnabled(true); if this is false make it true or remove this line
Here is the simplest solution that worked for me.
The ActionBarDrawerToggle has two types constructors. One of them take toolbar as a parameter. Use that (second one below) to get the animated hamburger.
ActionBarDrawerToggle(this, mDrawerLayout, R.string.content_desc_drawer_open,
R.string.content_desc_drawer_close);
ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.content_desc_drawer_open,
R.string.content_desc_drawer_close);` //use this constructor
You can try to make your own drawable for the hamburger icon like this.
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportHeight="24.0"
android:viewportWidth="24.0">
<path
android:fillColor="#ffffff"
android:pathData="M3,18h18v-2L3,16v2zM3,13h18v-2L3,11v2zM3,6v2h18L21,6L3,6z" />
</vector>
Then in your fragment/activity,
getSupportActionBar().setHomeAsUpIndicator(R.drawable.as_above);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
For other drawables, this might help: https://github.com/google/material-design-icons/blob/master/navigation/drawable-anydpi-v21/
I had the same problem and I found the simplest solution here:
appcompatv7-v21-navigation-drawer-not-showing-hamburger-icon
All I had to do was to call:
mDrawerToggle.syncState();
I had the same problem.
Get the ToolBar and then set Navigation icon
final android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.blablabla);
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setTitle("title");
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_list);
ok to hide back arrow use
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);
then find hamburger icon in web ->hamburger
and finally, set this drawable in your project with action bar method:
getSupportActionBar().setLogo(R.drawable.hamburger_icon);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
it's work with me
Maybe you can try this, but you will lose animation between arrow and hamburger icon
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
super.setContentView(R.layout.activity_menu_drawer_left);
_drawerToggle = new ActionBarDrawerToggle(this, _drawerLayout, R.string.drawer_opened, R.string.drawer_closed) {
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
changeDrawerIconOnDrawerClick(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
changeDrawerIconOnDrawerClick(R.drawable.ic_drawer);
}
};
//to change default icon to hamburger item initially
changeDrawerIconOnDrawerClick(R.drawable.ic_drawer); }
private void changeDrawerIconOnDrawerClick(int resourceId) {
//Drawable icon = ContextCompat.getDrawable(getApplicationContext(), resourceId);
Drawable icon = ResourcesCompat.getDrawable(getResources(), resourceId, null);
icon.setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
_drawerToggle.setDrawerIndicatorEnabled(false);
_drawerToggle.setHomeAsUpIndicator(icon);
}
Replace the default Up-arrow with your own drawable
getSupportActionBar().setHomeAsUpIndicator(R.drawable.hamburger);
Just Add the following in your onCreate method,
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, mDrawer, mToolbar, R.string.home_navigation_drawer_open, R.string.home_navigation_drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
}
};
mDrawer.addDrawerListener(toggle);
toggle.syncState();
and In strings.xml,
<string name="home_navigation_drawer_open">Open navigation drawer</string>
<string name="home_navigation_drawer_close">Close navigation drawer</string>
Use this constructor in MyActionBarDrawerToggle :
public MyActionBarDrawerToggle(AppCompatActivity host, DrawerLayout drawerlayout, SupportToolbar toolbar, int openedResource, int closedResource)
: base(host, drawerlayout, toolbar, openedResource, closedResource)
{
mHostActivity = host;
mOpenedResource = openedResource;
mClosedResource = closedResource;
}
and Call this method in teh mainActivity (Using AppCompatActivity)
mDrawerToggle = new MyActionBarDrawerToggle(
this, //Host Activity
mDrawerLayout, //DrawerLayout
mToolbar, //Toolbar
Resource.String.openDrawer, //Opened Message
Resource.String.closeDrawer //Closed Message
);
mDrawerLayout.AddDrawerListener(mDrawerToggle);
SupportActionBar.SetHomeButtonEnabled(true);
SupportActionBar.SetDisplayShowTitleEnabled(true);
mDrawerToggle.DrawerIndicatorEnabled = true;
mDrawerToggle.SyncState();
in onCreate():
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
supportInvalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
supportInvalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(drawerToggle);
drawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Backstack.get(MainActivity.this).goBack();
}
});
//actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
//getSupportActionBar().setDisplayHomeAsUpEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setHomeButtonEnabled(true);
And when setting up UP navigation:
private void setupViewsForKey(Key key) {
if(key.shouldShowUp()) {
drawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
drawerToggle.setDrawerIndicatorEnabled(true);
}
drawerToggle.syncState();
in JetPack it work for me
NavigationUI.setupWithNavController(vb.toolbar, nav)
vb.toolbar.navigationIcon = ResourcesCompat.getDrawable(resources, R.drawable.icon_home, null)