I am making an app and I want to put an action bar with a back arrow in a fragment.
So, I already have the fragment with the action bar but don't know how to put the back arrow on it.
Can you help me please?
Thank you,
Guilherme
This is the fragment with an action bar tag
Add following line in your fragment if you want to show the back button from the fragment :
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
It would be better that along with doing this. You add the parent of the activity in the manifest file to make sure that parent activity is opened when back arrow is pressed.
I have some thing like this for back button in toolbar instead of action bar.
In activity_main.xml :
<RelativeLayout 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/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.wolfmatrix.dummy.MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbarId"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="#color/colorPrimary">
<TextView
android:id="#+id/toolbarTextId"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textColor="#android:color/white"
android:textSize="14sp" />
</android.support.v7.widget.Toolbar>
<ImageButton
android:id="#+id/backButtonIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:gravity="left"
android:padding="10dp"
app:srcCompat="#drawable/ic_arrow_back_black_24dp" />
</RelativeLayout>
In styles.xml: use theme => Theme.AppCompat.Light.NoActionBar
In ic_arrow_back_black_24dp.xml, use this:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#ffffff"
android:pathData="M20,11H7.83l5.59,-5.59L12,4l-8,8 8,8 1.41,-1.41L7.83,13H20v-2z"/>
And now, toolbar has the back icon too.
Try below code
Implement OnBackStackChangedListener and add this code to your Fragment Activity.
#Override
public void onCreate(Bundle savedInstanceState) {
//Listen for changes in the back stack
getSupportFragmentManager().addOnBackStackChangedListener(this);
//Handle when activity is recreated like on orientation Change
shouldDisplayHomeUp();
}
#Override
public void onBackStackChanged() {
shouldDisplayHomeUp();
}
public void shouldDisplayHomeUp(){
//Enable Up button only if there are entries in the back stack
boolean canback = getSupportFragmentManager().getBackStackEntryCount()>0;
getSupportActionBar().setDisplayHomeAsUpEnabled(canback);
}
#Override
public boolean onSupportNavigateUp() {
//This method is called when the up button is pressed. Just the pop back stack.
getSupportFragmentManager().popBackStack();
return true;
}
add to your onCreate in the top
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
and add a function to the activity
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
getSupportFragmentManager().popBackStack();
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
good luck
Add below line after setcontentview()
//by doin that Back arrow will appear
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Create following overridden method after onCreate().
#Override
public boolean onSupportNavigateUp() {
finish();
return super.onSupportNavigateUp();
}
Related
I want to go from fragment to activity using back button using toolbar back icon.
The fragment is my navigation drawer item & activity is my MainActivity.
How do I do it?
You can use app:navigationIcon="?attr/homeAsUpIndicator" for that back navigation icon.
<android.support.v7.widget.Toolbar
android:id="#+id/toolbarId"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:navigationIcon="?attr/homeAsUpIndicator"/>
For navigation:
Toolbar toolbar = (ToolBar) getActivity().findViewById(R.id.toolbarId);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().onBackPressed();
}
});
Call this method in your fragment onCreateView
public void showBackButton() {
if (getActivity() instanceof ActionBarActivity) {
((ActionBarActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
Try this worked for me :
in XML:
<android.support.v7.widget.Toolbar
android:id="#+id/profileToolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
Create an back arrow icon in drawable folder. Name it 'ic_back_button'.
Not sure how :-
just right click on drawable > new > ImageAsset > Clip Art > Search back > select > OK > Finish (don't forget to change the name).
then Inside your fragment in onCreateView :
Toolbar toolbar = view.findViewById(R.id.profileToolbar);
toolbar.setNavigationIcon(R.drawable.ic_back_button);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().onBackPressed();
}
});
It might help in case if you want to come back from fragment to previous location.
Put this in your class with navController.
#Override
public boolean onSupportNavigateUp() {
navController.navigateUp();
return super.onSupportNavigateUp();
}
don't forget implement relevant dependency such as navigation and navigation UI.
Add this xml code to your fragment and try
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#FFFFFF"
android:layout_gravity="center"
android:gravity="center_horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title Here"
android:typeface="serif"
android:layout_gravity="center"
android:id="#+id/toolbar_title"
android:textSize="20sp"
android:textColor="#android:color/black"/>
<ImageView
android:id="#+id/ivback_water"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:padding="15dp"
android:scaleType="fitCenter"
android:layout_gravity="left"
android:background="#drawable/ic_arrow_back_black_24dp" />
</android.support.v7.widget.Toolbar>
You can easily do that, if you are using a Custom back button that is placed on your Custom top app bar, in the button's onClick() function you can call.. getActivity().onBackPressed();
it would work the same as if you have clicked the android navigation's back button...
I have written a piece of code as part of an app where I want to implement a back button on the action bar/tool bar such that when the button is pressed, the previous page (the page/fragment immediately before the current page/fragment) will be displayed.
This is the code for the ToolBar, DrawerLayout, NavigationView and getSupportActionBar():
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setVisibility(View.VISIBLE);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
I am unable to use ActionBar. For some reason (I don't know why), my Android studio/ program, will not allow me to use the ActionBar. So I am substituting that with the set/getSupportActionBar().
The function used in relation to this are:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_settings, 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();
switch (id) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
My activity_main.xml file is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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:fitsSystemWindows="true"
android:id="#+id/activity_main"
android:orientation="vertical"
tools:openDrawer="start"
tools:context="com.example.albin.settings_menu.SettingsActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff">
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:popupTheme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:title="Settings"/>
<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">
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar">
</FrameLayout>
<android.support.design.widget.NavigationView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
android:layout_marginTop="-24dp"
app:menu="#menu/options_menu" />
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
</LinearLayout>
The problem is that I don't know which is the useful code, which is the useless code and how to mix/join/(add additional codes to) these (codes, methods, variables/objects, fragments, xml layouts) to get the desired outcome, that is, the application of a back button on the action bar/tool bar.
Most of the code above is implemented for the up button, not the back button. I have read at several places that up and back buttons are not the same.
I tried several links on internet as well as on this site, but none of them has just what I need.
Hope someone can give me an clear answer...
You can include the back icon in ToolBar:
Initialize ToolBar:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
You can use an drawable icon as a back button.
toolbar.setNavigationIcon(R.drawable.your_drawable_icon);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// what do you want here
}
});
If you do not want to use drawable icon then:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// what do you want here
}
});
Actually your layout having that issue because you have added toolbar in RelativeLayout so drawer layout is overlapping on it that's why you would not able to click on back arrow, i have fix your layout see below
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:navigationIcon="#drawable/ic_back_black"
app:popupTheme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:title="Settings" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/options_menu" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
The simplest way would be to add parent activity in manifest file as developer docs suggest.
<activity
android:name=".ChildActivity"
android:parentActivityName=".ParentActivity" >
and java code you already have done it, setSupportActionbar and setHomeAsUpEnabled.
Edited :
its necessary to add up action for icon to be visible, as mentioned in
Android Developer Docs
So toolbar gives added flexibility to modify title-bar in Android.
As far as why getActionBar is not working and you are compelled to use getSupportActionBar is because you must be using SupportLibrary. SupportLibrary gives backward compatibility to earlier SDK versions.
If you want to modify your title-bar/header/action-bar extensively
then use toolbar otherwise use action-bar.
Add a navigation click listener to your toolbar , like below
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
If you are referencing some actions from the action bar, such as a Save action or a Share one, and you are overriding onOptionsItemSelected method, then you need to define the behavior when the back or home button is clicked:
#Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
//save stuff
break;
//this is what you need to add to reference again back/home button
case android.R.id.home:
//do your stuff here, usually back to the home or close the current activity
getActivity().finish();
break;
default:
break;
}
return true;
I want to implement the up button in an android application with only one activity that changes its content with different fragment.
I used the default navigation drawer activity provided by android studio where i added a frameLayout to the content_main.
In the fragment where i want the up botton to be shown i added this line of code in the onCreateView method:
ActionBar actionBar = ((AppCompatActivity)getActivity()).getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
ad this line in the onCreate method:
setHasOptionsMenu(true);
and i added the method to catch the click of it:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
Log.w("second fragment","clicked back");
return true;
}
return super.onOptionsItemSelected(item);
}
in the activiy i set onCreateOptionsMenu like this:
#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;
}
but the click of it isn't triggered.
I tried to add a setting button and it is triggered.
I already read a lot of question about this but i can't figure out how to resolve it
setHasOptionsMenu(true) should be called in method onCreate() to let the FragmentManager know that your fragment needs to receive options menu callbacks.
I believe you use this constructor for ActionBarDrawerToggle which takes a Toolbar as a parameter. If you are using this constructor, onOptionsItemSelected will not be called if you click on the indicator. There are questions/answers regarding this problem, for example:
AppCompat v7 Toolbar onOptionsItemSelected not called
But for me, none of them worked perfectly so I used the Toolbar-specific constructor and here it's a workaround for my case. I put a transparent view on top of the toolbar which is "visible" only when I show the back button and I handle the click myself (calling onBackPressed() in my case).
I know it's a kind of hack, but it needed and worked for me.
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/main_background">
<android.support.design.widget.AppBarLayout
android:id="#+id/appBar"
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="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"/>
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/layoutMainContent"
android:layout_below="#id/appBar"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
<!-- The important view -->
<View
android:id="#+id/viewFakeBack"
android:layout_width="56dp"
android:layout_height="56dp"
android:clickable="true"
android:visibility="gone"/>
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigationView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/navigation_drawer"/>
</android.support.v4.widget.DrawerLayout>
Try by using switch(...) case statement.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//this will make Hamburger button clickable.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
//this will make the HomeAsUpIndicator button clickable.
switch (item.getItemId()) {
case android.R.id.home:
Log.w("second fragment","clicked back");
break;
}
return super.onOptionsItemSelected(item);
}
Hope this will help you.
I have the following part of the xml code that defines my toolbar:
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:columnCount="5"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:useDefaultMargins="true"
android:alignmentMode="alignBounds"
android:columnOrderPreserved="false">
<android.support.v7.widget.Toolbar android:id="#+id/toolbar_setting"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"/>
... // other code here
and the code in the SettingsActivity (derived from AppCompatActivity) is as follows:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
// Set toolbar, allow going back.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_setting);
toolbar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Settings");
When compiling and running the code I see a toolbar as follows:
but a click on the left-arrow does not get me back to the previous menu. What am I missing here?
You can access that little arrow by android.R.id.home :
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return(super.onOptionsItemSelected(item));
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
If you try this code , when you click arrow, it will act like your back button pressed.
in onOptionsItemSelected you need to listen for the click then do something
case android.R.id.home:
// do something with the click
break;
As you need to go one level up, make the following changes in your AndroidManifest.xml.
<activity
android:name=".CurrentActivity"
android:parentActivityName=".OneLevelUpActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".OneLevelUpActivity" />
</activity>
In onCreate() add toolbar.setHomeButtonEnabled(true);
The <meta-data> is to support earlier API versions (<API level 16).
I have a simple android.support.v7.widget.Toolbar and all I am trying to do is to open a NavigationDrawer by pressing the "hamburger" icon in the top left corner. The "hamburger" button is visible, and when I start to pull from the left I see the animation on the button but pressing the button does not open/close the NavigationDrawer as I expect. I have followed the [Google Documentation][1] and still am not able to figure this out. Sorry for any confusion, below is the simplified code I am currently attempting to use:
public class MainActivity extends AppCompatActivity implements
View.OnClickListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("NICK", "button button button..................");
}
});
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
NavigationView n = (NavigationView) findViewById(R.id.nav);
mDrawerLayout.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Log.d("NICK", "button button button..................");
}
});
//mDrawerLayout.setDrawerListener(mDrawerToggle);
n.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
////.......
}
mDrawerLayout.closeDrawers(); // CLOSE DRAWER
return true;
}
});
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d("NICK","CWECNEWKVNERIPNVIEWNFVIPEWNVIPEWNVPIEWNVPIEWNVPIEWNVPIRWNVPRWVPO");
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START); // OPEN DRAWER
Log.d("NICK","CWECNEWKVNERIPNVIEWNFVIPEWNVIPEWNVPIEWNVPIEWNVPIEWNVPIRWNVPRWVPO");
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.drawer, menu);
return true;
}
}
}
And as it is I do not get any of the log debug statements when running.
This is essentially the issue I have: https://stackoverflow.com/a/26636045/1489990. I've followed this and it just doesn't work.
It is my understanding that setNavigationOnClickListener is called when the hamburger icon is pressed, and this is where I am focusing my efforts is to get the event handled properly because when I press the button I do not get my log statement. Let me know if this idea is incorrect. https://developer.android.com/reference/android/widget/Toolbar.html#setNavigationOnClickListener(android.view.View.OnClickListener)
My Layouts:
ActivityMain.xml
<RelativeLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/d"
android:background="#drawable/home_wall">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:layout_marginBottom="10dp"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:layout_marginTop="25dp"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" />
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:id="#+id/drawer"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<ImageView
android:layout_width="fill_parent"
android:layout_height="200dp"
android:id="#+id/imageView"
android:src="#drawable/trans2"
android:layout_alignParentTop="true"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:paddingBottom="300dp" />
<RelativeLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/d8"
android:layout_alignParentTop="true"
android:layout_alignLeft="#+id/imageView"
android:layout_alignStart="#+id/imageView"
android:paddingTop="0dp">
<Button
android:layout_width="75dp"
android:layout_height="50dp"
android:text="Gallery"
android:id="#+id/save_button"
android:background="#dd2c00" android:textColor="#fff"
android:layout_below="#+id/Purchases"
android:layout_toRightOf="#+id/start_button"
android:layout_toEndOf="#+id/start_button" />
<Button
android:layout_width="125dp"
android:layout_height="50dp"
android:text="Store"
android:id="#+id/Purchases"
android:background="#ff6e40" android:textColor="#fff"
android:layout_above="#+id/instructions_button6"
android:layout_toLeftOf="#+id/start_button"
android:layout_toStartOf="#+id/start_button"
android:layout_marginBottom="98dp" />
<Button
android:layout_width="75dp"
android:layout_height="50dp"
android:text="Help"
android:id="#+id/instructions_button6"
android:background="#dd2c00" android:textColor="#fff"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="#+id/start_button"
android:layout_toStartOf="#+id/start_button"
android:layout_marginLeft="5dp"
android:layout_marginBottom="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="300dp"
android:text="Start"
android:id="#+id/start_button"
android:background="#ff3d00"
android:textColor="#fff"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp" />
<Button
android:layout_width="125dp"
android:layout_height="50dp"
android:text="Achievements"
android:id="#+id/Scores"
android:background="#ff6e40" android:textColor="#fff"
android:layout_alignTop="#+id/Purchases"
android:layout_toRightOf="#+id/start_button"
android:layout_toEndOf="#+id/start_button" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to the quiz!"
android:id="#+id/textView"
android:textColor="#fff"
android:textSize="20dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp" />
<!-- sign-in button -->
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="110dp"
android:layout_height="50dp"
android:layout_above="#+id/start_button"
android:layout_centerHorizontal="true"
android:visibility="visible" />
<!-- sign-out button -->
<Button
android:id="#+id/sign_out_button"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:text="Sign Out"
android:visibility="invisible"
android:background="#dd4b39"
android:textColor="#fff"
android:layout_alignTop="#+id/sign_in_button"
android:layout_centerHorizontal="true"
android:layout_marginTop="160dp" />
</RelativeLayout>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#fff"
android:id="#+id/nav"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/drawer"/>
</android.support.v4.widget.DrawerLayout>
Drawer.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_menu"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:title="Google Play Games"
android:icon="#drawable/ic_local_airport_white_48dp">
<menu>
<item
android:id="#+id/Sign_in_drawer"
android:icon="#drawable/games_controller_grey"
android:title="Sign in" />
<item
android:id="#+id/ach"
android:icon="#drawable/games_achievements"
android:title="Achievements" />
</menu>
</item>
<item android:title="Start a Quiz"
android:icon="#drawable/ic_local_airport_white_48dp">
<menu>
<item
android:id="#+id/quizStart25"
android:icon="#drawable/ic_local_airport_white_48dp"
android:title="25 Questions" />
<item
android:id="#+id/quizStart10"
android:icon="#drawable/ic_local_airport_white_48dp"
android:title="10 Questions" />
</menu>
</item>
<group
android:checkableBehavior="single">
<item
android:id="#+id/gallery"
android:icon="#drawable/ic_photo_library_white_48dp"
android:title="Gallery" />
<item
android:id="#+id/stats"
android:icon="#drawable/ic_toc_white_48dp"
android:title="Statistics" />
<item
android:id="#+id/store"
android:icon="#drawable/ic_shop_white_48dp"
android:title="Store" />
<item
android:id="#+id/settings"
android:icon="#drawable/ic_settings_white_48dp"
android:title="Settings" />
<item
android:id="#+id/about"
android:icon="#drawable/ic_info_white_48dp"
android:title="About" />
</group>
<item android:title="Support">
<menu>
<item
android:id="#+id/help_drawer"
android:icon="#drawable/ic_help_white_48dp"
android:title="Help" />
<item
android:id="#+id/report"
android:icon="#drawable/ic_report_problem_white_48dp"
android:title="Contact Developer" />
<item
android:id="#+id/GPlusCommunity"
android:icon="#drawable/btn_g_white_normal"
android:title="Google+ Community" />
</menu>
</item>
In your ActivityMain.xml, the toolbar is outside of the DrawerLayout. That's the problem. If you want Toolbar to interact with DrawLayout, Toolbar needs to be a child of DrawerLayout.
To fix the problem, make DrawerLayout the root of your activity. Here's the documentation. The relevant quote is:
To add a navigation drawer, declare your user interface with a
DrawerLayout object as the root view of your layout. Inside the
DrawerLayout, add one view that contains the main content for the
screen (your primary layout when the drawer is hidden) and another
view that contains the contents of the navigation drawer.
So basically, structure your ActivityMain.xml to be something like this:
<android.support.v4.widget.DrawerLayout ...>
<RelativeLayout ...>
<android.support.v7.widget.Toolbar .../>
<!-- Your other content goes here -->
</RelativeLayout>
<android.support.design.widget.NavigationView .../>
</android.support.v4.widget.DrawerLayout>
That should take care of the problem.
Override onOptionsItemSelected method and use below
if(item.getItemId() == android.R.id.home){ // use android.R.id
mDrawerLayout.openDrawer(Gravity.LEFT);
}
You need to sync the drawer toggle:
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
EDIT: That code is working for me (copied from your post)
public class TempActivity extends AppCompatActivity {
private ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.temp);
setupDrawer();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(final MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
private void setupDrawer() {
Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.my_drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,toolbar,R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
}
<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/my_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<RelativeLayout
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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:text="DRAMER MENU" />
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
But if you are using the new NavigationView, then you don't need the toggle etc. Here is a good example how to use it.
I fixed it by giving openable which is drawerLayout to navigateUp function.
More info navigateUp Doc
override fun onSupportNavigateUp(): Boolean {
val navController = this.findNavController(R.id.host_fragment)
return NavigationUI.navigateUp(navController,drawer_layout)
}
If it helps somebody, to me it happened the same because of the stupid error of calling setSupportActionBar(toolbar) two times. Just call it once in onCreate method and never again. My mistake was I called it later in another method.
Use ActionBarDrawerToggle and implement public boolean onOptionsItemSelected(MenuItem item)
Toolbar DOES NOT have to be within a DrawerLayout, it's not likely to be the cause of this issue. toggle.onOptionsItemSelected(item) looks for the ID of the item selected and if it is android.R.id.home then the drawer's visibility is toggled. Thus Toolbar, or any View that creates a Home MenuItem, can be placed anywhere in your layout.
Within your activity:
ActionBarDrawerToggle toggle;
private void setupDrawerToggleInActionBar() {
// assuming a Toolbar has been initialized in your onCreate
this.setSupportActionBar(toolbar);
// setup the action bar properties that give us a hamburger menu
ActionBar actionBar = this.getSupportActionBar();
if(actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
// the toggle allows for the simplest of open/close handling
toggle = new ActionBarDrawerToggle(this,
drawerLayout,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
// drawerListener must be set before syncState is called
drawerLayout.setDrawerListener(toggle);
toggle.setDrawerIndicatorEnabled(true);
toggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// This is required to make the drawer toggle work
if(toggle.onOptionsItemSelected(item)) {
return true;
}
/*
* if you have other menu items in your activity/toolbar
* handle them here and return true
*/
return super.onOptionsItemSelected(item);
}
Simply call function onOptionsItemSelected(MenuItem menuItem) of ActionBarDrawerToggle class on activity options menu managing function like below.
mDrawerToggle= new ActionBarDrawerToggle(activity, drawerLayout, R.string.nav_drawer_accessbility_drawer_open,
R.string.nav_drawer_accessbility_drawer_close);
#Override
public boolean onOptionsItemSelected(final android.view.MenuItem item) {
navigation().getOptionsMenuInflater(this).closeSearchView();
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this behavior.
mDrawerToggle.onOptionsItemSelected(item);
return super.onOptionsItemSelected(item);
}
OR
override onOptionsItemSelected of activity like below
public boolean onOptionsItemSelected(MenuItem item) {
if (item != null && item.getItemId() == android.R.id.home) {
toggle();
}
return super.onOptionsItemSelected(item);
}
private void toggle() {
if (mDrawerLayout.isDrawerVisible(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START);
} else {
mDrawerLayout.openDrawer(GravityCompat.START);
}
}
For the drawer toggle you need to set "display home as up" to false:
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
As i have no specific answer to your problem, i want to suggest a completely different approach:
In my projects im using the Material Drawer developed by Mike Penz.
Its looks really nice, is easy to implement, and there is not much you have to worry about.
So if you cant find a solution for your problem, you could give it a try.
While accepted answer here works alright however, as they say "Prevention is better than cure".. Adding mDrawerToggle.syncState(); in onPostCreate and onConfigurationChanged() wroks much better as answerd by #mbmc above:
#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);
}
After a lot of different problems I found a way to make it work putting Toolbar Widget inside AppBarLayout.
Be sure that there is no other layout on top of widget toolbar!
<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:id="#+id/drawable_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
xmlns:android="http://schemas.android.com/apk/res/android">**
<androidx.appcompat.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_page_toolbar"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:background="#color/colorPrimaryDark"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>**
.... YOUR LAYOUT ...
</RelativeLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:layout_marginBottom="3dp"
app:menu="#menu/navigation_menu">
</com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
Idk why...but changing return value to false rather than true fixed the ham Icon for me. on onOptionItemSelected override method
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if(item.getItemId() == R.id.logout){
ParseUser.logOut();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
Toast.makeText(this, "Logout Successful!", Toast.LENGTH_SHORT).show();
} else if(item.getItemId() == R.id.action_settings){
Toast.makeText(this, "No setting to update! Will be available later...", Toast.LENGTH_SHORT).show();
}
return true; // here change this to false
}
If none of the above answer works, please cross check again,
First you need to call setSupportActionBar(toolbar); and then do the necessary work for nav drawer. I wasted my 2 hours because of this silly mistake.
I had the same problem. However, it did not occur on all fragments. It occurred on one particular fragment.
Firstly, please follow #hungryghost 's answer mentioned above. Then do the following.
Adding the following piece of code helped the drawer open on click of the hamburger icon. It worked flawlessly for me. Thank you very much. :) My sincere apologies if this isn't the right way.
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int itemId = item.getItemId();
if(itemId == android.R.id.home){
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
I have found a simple solution to this problem is to call the setSupportActionBar(toolbar) method before the navigation drawer functions.