Android - Switch Actionbar Back Button to Navigation Button

How to implement the Android ActionBar back button?

Selvin already posted the right answer. Here, the solution in pretty code:

public class ServicesViewActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// etc...
getActionBar().setDisplayHomeAsUpEnabled(true);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

The function NavUtils.navigateUpFromSameTask(this) requires you to define the parent activity in the AndroidManifest.xml file

<activity android:name="com.example.ServicesViewActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.ParentActivity" />
</activity>

See here for further reading.

Android - Switch ActionBar Back Button to Navigation Button

If I assume you're using android.support.v4.widget.DrawerLayout in your layout, then this approach may work for you; I've only tested on API 21 but given it's mostly using the support libraries, it should work (famous last words) on lower or higher targets.

import android.support.v7.app.ActionBarDrawerToggle
import android.support.v4.widget.DrawerLayout

ActionBarDrawerToggle mDrawerToggle;
DrawerLayout drawerLayout;
private boolean mToolBarNavigationListenerIsRegistered = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
// Get DrawerLayout ref from layout
drawerLayout = (DrawerLayout)findViewById(R.id.drawer);
// Initialize ActionBarDrawerToggle, which will control toggle of hamburger.
// You set the values of R.string.open and R.string.close accordingly.
// Also, you can implement drawer toggle listener if you want.
mDrawerToggle = new ActionBarDrawerToggle (this, drawerLayout, mToolbar, R.string.open, R.string.close);
// Setting the actionbarToggle to drawer layout
drawerLayout.addDrawerListener(mDrawerToggle);
// Calling sync state is necessary to show your hamburger icon...
// or so I hear. Doesn't hurt including it even if you find it works
// without it on your test device(s)
mDrawerToggle.syncState();
}

/**
* To be semantically or contextually correct, maybe change the name
* and signature of this function to something like:
*
* private void showBackButton(boolean show)
* Just a suggestion.
*/
private void enableViews(boolean enable) {

// To keep states of ActionBar and ActionBarDrawerToggle synchronized,
// when you enable on one, you disable on the other.
// And as you may notice, the order for this operation is disable first, then enable - VERY VERY IMPORTANT.
if(enable) {
//You may not want to open the drawer on swipe from the left in this case
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
// Remove hamburger
mDrawerToggle.setDrawerIndicatorEnabled(false);
// Show back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// when DrawerToggle is disabled i.e. setDrawerIndicatorEnabled(false), navigation icon
// clicks are disabled i.e. the UP button will not work.
// We need to add a listener, as in below, so DrawerToggle will forward
// click events to this listener.
if(!mToolBarNavigationListenerIsRegistered) {
mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Doesn't have to be onBackPressed
onBackPressed();
}
});

mToolBarNavigationListenerIsRegistered = true;
}

} else {
//You must regain the power of swipe for the drawer.
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);

// Remove back button
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
// Show hamburger
mDrawerToggle.setDrawerIndicatorEnabled(true);
// Remove the/any drawer toggle listener
mDrawerToggle.setToolbarNavigationClickListener(null);
mToolBarNavigationListenerIsRegistered = false;
}

// So, one may think "Hmm why not simplify to:
// .....
// getSupportActionBar().setDisplayHomeAsUpEnabled(enable);
// mDrawer.setDrawerIndicatorEnabled(!enable);
// ......
// To re-iterate, the order in which you enable and disable views IS important #dontSimplify.
}

The solution uses ActionBarDrawerToggle.setDrawerIndicatorEnabled to toggle the visibility of the hamburger icon and ActionBar.setDisplayHomeAsUpEnabled for visibility of the Up button, essentially making use of their respective drawable resources.

Other assumptions

  • Your Activity theme extends Theme.AppCompat.Light.NoActionBar.

How to display back button on action bar in android another activity

Just add code this in the onCreate method of your [CurrentActivity].java file.

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

And this line of code will just add a back button in your Action Bar, but nothing would happen after tapping that right now.

And add this in your [CurrentActivity].java, this will add the working of that button:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:

Intent intent = new Intent(CurrentActivity.this, MainActivity.class);
startActivity(intent);
finish();
return true;

default:
return super.onOptionsItemSelected(item);
}
}

And replace CurrentActivity to your activity name and replace MainActivity to the activity you want to send user after pressing back button

Android-switching navigation burger icon to back icon

You need to change the icon of the Drawer Toggle while opening the fragment.When the user clicks back button from the fragment, pop back stack and reset the support action bar indicator as hamburger. You might have to override

onSupportNavigateUp()

method in your activity if back button not working

 @Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}

Good luck.

EDIT

Here is a sample code to implement the behaviour you need.

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.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
Toolbar toolbar;
private CharSequence mTitle;
ActionBarDrawerToggle mDrawerToggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = getTitle();
mNavigationDrawerItemTitles= getResources().getStringArray(R.array.navigation_drawer_items_array);
mDrawerLayout = findViewById(R.id.drawer_layout);
mDrawerList = findViewById(R.id.left_drawer);

setupToolbar();

DataModel[] drawerItem = new DataModel[2];

drawerItem[0] = new DataModel(R.drawable.ic_menu_camera, "Connect");
drawerItem[1] = new DataModel(R.drawable.ic_menu_gallery, "Fixtures");

DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.list_view_item_row, drawerItem);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerLayout = findViewById(R.id.drawer_layout);
setupDrawerToggle();
}

private class DrawerItemClickListener implements ListView.OnItemClickListener {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}

}

private void selectItem(int position) {

Fragment fragment = null;

switch (position) {
case 0:
fragment = new TestFragment();
break;
case 1:
fragment = new TestFragment2();
break;
default:
break;
}

if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(fragment.getTag()).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
showBackButton(true);
mDrawerLayout.closeDrawer(mDrawerList);

}
}

@Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}

void setupToolbar(){
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(true);
}

void setupDrawerToggle(){
mDrawerToggle = new android.support.v7.app.ActionBarDrawerToggle(this,mDrawerLayout,toolbar,R.string.app_name, R.string.app_name);
//This is necessary to change the icon of the Drawer Toggle upon state change.
mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(mDrawerToggle.isDrawerIndicatorEnabled()){
mDrawerLayout.openDrawer(GravityCompat.START);
}else{
onBackPressed();
}
}
});
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}

public void showBackButton(boolean isBack){
mDrawerToggle.setDrawerIndicatorEnabled(!isBack);
getSupportActionBar().setDisplayHomeAsUpEnabled(isBack);
mDrawerToggle.syncState();
}

@Override
public void onBackPressed() {
if(mDrawerLayout.isDrawerOpen(GravityCompat.START)){
mDrawerLayout.closeDrawer(GravityCompat.START);
}else{
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
} else {
super.onBackPressed();
}
showBackButton(false);
setTitle(getTitle());
}
}

@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}

Check the onBackPressed(), showBackButton() and setupDrawerToggle methods.

Back Button in ActionBar of App

I had the same problem once. Just like you, things like checking if Android.R.id.home is clicked didn't work.
But I solved it using that:

Set navigation listener to toolbar:

toolbar.setToolbarNavigationClickListener(v -> onBackPressed());

If it should be within fragment:

  1. Create an public method in activity.
  2. In fragment's onAttach (or later) cast getActivity() to your activity and call method you was defined previously.

Example:

// YourActivity
public void setHomeListener(OnLickListener listener){
toolbar.setToolbarNavigationClickListener(listener);
}

//Fragment's onCreate
((YourActivity)getActivity()).setHomeListener(v -> onBackPressed());

//Fragment's onDestroy
((YourActivity)getActivity()).setHomeListener(null);

And, of course, set home us up enabled to show back arrow.

EDIT

if you don't use labmdas u should use:

(YourActivity)getActivity()).setHomeListener(new OnClickListener() {
@Override
public void onClick(View v) {
YourFragment.this.onBackPressed();
}
});

Add back button to action bar

After setting
actionBar.setHomeButtonEnabled(true);

Add the following code:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; goto parent activity.
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}

How to enable back press button on the right side of action bar?

What you did is enabled the action-bar's back functionality on click/touch event. If you want a button at the right of the action bar, the best/easy thing you can do is to add an overflow menu, for which you can set-up any icon you want.

There are lots of tutorials on how to do this (for ex. http://www.techotopia.com/index.php/Creating_and_Managing_Overflow_Menus_on_Android).

Essential points are as follows.

  1. Create the layout/items for the overflow menu (filename should match with the one in the 2nd step).

    <menu xmlns:android="http://schemas.android.com/apk/res/android" >  
    <item
    android:id="@+id/menu_settings"
    android:orderInCategory="1"
    android:showAsAction="never"
    android:icon="@drawable/overflow_menu_icon"
    android:title="@string/menu_settings" />
    </menu>
  2. Init the overflow inside the onCreateOptionsMenu() function, where activity_menu_app is the name of the .xml file created in the previous step.

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_menu_app, menu);
    return true;
    }
  3. Catch the touch events of the menu items inside onOptionsItemSelected() function.

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_settings:
    // do your stuff here
    return true;
    default:
    return super.onOptionsItemSelected(item);
    }
    }


Related Topics



Leave a reply



Submit