83

with the help of these Android Docs.I am trying to do a action bar Back button.I get an Action Bar Back Button like these below image:

enter image description here

Output:

But My problem is After watching the Gallery images I press the action bar back button.

Then it is not working.But it have to go back to previous page.

Listed below are the codings.

GalleryActivity.java:

    import android.app.ActionBar;
    import android.os.Bundle;
    import android.support.v4.app.FragmentActivity;
    import android.support.v4.app.NavUtils;
    import android.view.MenuItem;

    import com.fth.android.R;

   public class GalleryActivity extends FragmentActivity {

    private int position;
    private static String id;
    private static String name;
    private DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
    private ViewPager mViewPager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_gallery);

            position = getIntent().getExtras().getInt("position");

            id = getIntent().getExtras().getString("id");

            name = getIntent().getExtras().getString("name");

            mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager());

            // Set up action bar.
            final ActionBar actionBar = getActionBar();


            actionBar.setDisplayHomeAsUpEnabled(true);

           // getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME|ActionBar.DISPLAY_USE_LOGO|ActionBar.DISPLAY_HOME_AS_UP);

            // Set up the ViewPager, attaching the adapter.
            mViewPager = (ViewPager) findViewById(R.id.pager);
            mViewPager.setAdapter(mDemoCollectionPagerAdapter);
        }

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

                    Intent upIntent = new Intent(this, HomeActivity.class);
                    upIntent.putExtra("position", position);
                    if (NavUtils.shouldUpRecreateTask(this, upIntent)) {

                        TaskStackBuilder.from(this)
                                .addNextIntent(upIntent)
                                .startActivities();
                        finish();
                    } else {

                        NavUtils.navigateUpTo(this, upIntent);
                    }
                    return true;
            }
            return super.onOptionsItemSelected(item);
        }


      }

GalleryDetailFragment.java:

import com.sit.fth.model.GalleryDetail;
import com.sit.fth.util.APIServiceHandler;
import com.sit.fth.util.AppConstants;
import com.sit.fth.util.AppPromoPager;

public class GalleryDetailFragment extends BaseFragment implements
        PromoPagerListener {


    private TextView countView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        this.setHasOptionsMenu(true);
        id = getArguments().getString("id");
        name = getArguments().getString("name");
        View view = inflater.inflate(R.layout.app_pager, null);



        return view;
    }

}

Anybody can help me if you know how to solve these.Thank You.

Stephen
  • 9,899
  • 16
  • 90
  • 137
  • 1
    Have you tried to declare ParentActivities in AndroidManifest? – x90 Jun 04 '14 at 08:58
  • are you sure want to define android:parentActivityName="com.sit.fth.activity.HomeActivity" to com.sit.fth.activity.HomeActivity? You should define HomeActivity as parent activity to GalleryActivity for example. Not to itself. – x90 Jun 04 '14 at 09:06
  • @x90 HomeActivity is a mainActivity(Parent Activity) – Stephen Jun 04 '14 at 09:08

14 Answers14

189

I solved these problem by adding the below coding in GalleryActivity.

ActionBar actionBar;
actionBar=getActionBar();

actionBar.setDisplayHomeAsUpEnabled(true);

@Override
public boolean onOptionsItemSelected(MenuItem item) { 
        switch (item.getItemId()) {
        case android.R.id.home: 
            onBackPressed();
            return true;
        }

    return super.onOptionsItemSelected(item);
}

In MainActivity:

Previously,

public class HomeActivity extends BaseActivity

Then I change into

public class HomeActivity extends FragmentActivity

In GalleryFragment:

I use Intent to pass it to the GalleryActivity.

@Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        Gallery gallery = (Gallery) arg0.getAdapter().getItem(arg2);

        Intent intent = new Intent(getActivity(), GalleryActivity.class);
        intent.putExtra("position", position);
        intent.putExtra("id", gallery.getGalId());
        intent.putExtra("name", gallery.getAlbumTitle());
        startActivity(intent);

        // mCallback.OnGalItemSelected(gallery.getGalId(),gallery.getAlbumTitle());
    } 
Stephen
  • 9,899
  • 16
  • 90
  • 137
  • 1
    Spot on! `onBackPressed` is exactly what I was looking for. One of my settings screen was getting opened from several screens and I wanted to go back to the very same activity which opened it. What is this special id `android.R.id.home` in context of android activities? – RBT Aug 19 '18 at 09:32
  • @RBT Navigate up to parent Activity(https://developer.android.com/training/implementing-navigation/ancestral#java). Please read that. – Stephen Aug 19 '18 at 15:22
  • Using `onBackPressed` in home action of your OptionsMenu is not recommended: the up button (back arrow on top left corner) is used to navigate within an app based on the hierarchical relationships between screens, the system Back button is used to navigate, in reverse chronological order, through the history of screens the user has recently worked with. You can read more here: http://developer.android.com/design/patterns/navigation.html – Michele Aug 23 '20 at 14:01
48

Please read this

you should have something like this:

    <activity
        android:name="com.sit.fth.activity.HomeActivity"
        android:screenOrientation="portrait">

    </activity>
    <activity
        android:name="com.sit.fth.activity.GalleryActivity"
        android:screenOrientation="portrait"
        android:parentActivityName="com.sit.fth.activity.HomeActivity">

    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.sit.fth.activity.HomeActivity"/>

   </activity>


then calling NavUtils.navigateUpFromSameTask(this) will cause navigating to parent activity (HomeActivity).

x90
  • 2,140
  • 15
  • 25
  • @Stephen idle where? And i still don't understand from which activity to which activity you want navigate. – x90 Jun 04 '14 at 09:26
  • `Gallery Detail Fragment` to `Gallery Activity`.I shown in image also – Stephen Jun 04 '14 at 09:29
  • @Stephen In which activity `GalleryDetailFragment` is hosted? – x90 Jun 04 '14 at 10:12
  • @Stephen i understand. But every fragment should be hosted/attached/connected/belong to Activity. I am asking for which activity belongs your fragment. – x90 Jun 04 '14 at 10:16
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/55053/discussion-between-stephen-and-x90). – Stephen Jun 04 '14 at 10:17
  • this method destroys the previous activity, if you want to preserve the state refer to solution above this – Abhi Soni Dec 28 '16 at 17:18
  • It's a right answer. Because answer selected as `Solution` is the hack. It works but it's bad practice which forces you to use redundant code. – VKostenc May 19 '17 at 10:45
45

You need to call setDisplayHomeAsUpEnabled(true) method in the onCreate method and override onSupportNavigateUp() and call onBackPressed() in it as below. That's it. done :)

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_help);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

@Override
public boolean onSupportNavigateUp() {
    onBackPressed();
    return true;
}
Chanaka Fernando
  • 2,176
  • 19
  • 19
  • Why? I tested it adding only android:parentActivityName=".activities.MainActivity" to the manifest and it was enough with this one device I tested it with. – David Jul 09 '19 at 15:38
  • Although this works, please double-check that you have the `android:parentActivityName` set for your activity before resorting to manually calling `onBackPressed`. See https://stackoverflow.com/a/24033351/1563833 – Wyck Sep 16 '20 at 16:02
  • 1
    For Kotin: override fun onSupportNavigateUp(): Boolean { onBackPressed() return true } – Aathil Ahamed Jan 13 '21 at 02:48
14

You have just to add the following line to the activity in the manifest.xml. The parent activity is the activity to which you want to go back.

    android:parentActivityName=".activities.MainActivity"
scientist
  • 141
  • 1
  • 5
10

Try like

First of all you need to use addToBackStack() before commit() for Fragments

@Override
     public boolean onOptionsItemSelected(MenuItem item) {
         switch (item.getItemId()) {
         // Respond to the action bar's Up/Home button
         case android.R.id.home:
             if(getSupportFragmentManager().getBackStackEntryCount()>0)
                getSupportFragmentManager().popBackStack();
             return true;
         }
         return super.onOptionsItemSelected(item);
     } 
Amit Gupta
  • 8,914
  • 1
  • 25
  • 33
8

Best and easy answer is add the parent activity name in Manifest file, so Actionbar back button will work.

For that under that Activity tag of Manifest File use android:parentActivityName=".MyCustomParentActivity"

Vaishakh
  • 1,126
  • 10
  • 10
3

if the home button is shown. you should add an action to the home button through onOptionItemSelected fun (arrow in your case) by default there's no action. so it's totally normal that it's not working. Please add this fun to your activity :

 override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when {
            item.itemId == android.R.id.home -> {
                finish()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
Brahem Mohamed
  • 342
  • 2
  • 5
1

None of the answers provided here worked for me. I had to put the switch inside the onMenuItemSelected method. I'm aware this is not what is stated in the Android documentation, but still, it worked, so I just thought I'd leave this here for people who run into the same issue. My problem involved an Activity instead of a Fragment though, but that should be pretty much the same.

class FooActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // ...

        getActionBar().setHomeButtonEnabled(true);
        getActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                return true;
        }

        return false;
    }
}
PLPeeters
  • 1,009
  • 12
  • 26
1

To me, I had to set mDrawerToggle.setToolbarNavigationClickListener(...) to a listener that triggers the back action. Otherwise it does nothing. This is what the source code of ActionBarDrawerToggle looks like:

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    if (mDrawerIndicatorEnabled) {
      toggle();
    } else if (mToolbarNavigationClickListener != null) {
      mToolbarNavigationClickListener.onClick(v);
    }
  }
});

So the default behaviour is actually to call our listener, and not do any magic on its own.

daniel.gindi
  • 3,457
  • 1
  • 30
  • 36
1

Use on SupportNavigateUp() method and call onBackPressed in this method.

Felipe Augusto
  • 7,733
  • 10
  • 39
  • 73
Raj Godara
  • 21
  • 1
0

onCreate

{
    ...
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            resetActionBar();
    ...
 }


public void resetActionBar()
    {
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

 @Override
          public void onBackPressed() {
            FragmentManager fm = getSupportFragmentManager();
            int count = fm.getBackStackEntryCount();
            if(count == 0) {
                // Do you want to close app?
                showDialog();
            }else{
                super.onBackPressed();
            }
        }


    @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();
            Log.i("coming", "comming");
            //noinspection SimplifiableIfStatement
            if(id==android.R.id.home){
                if (getSupportFragmentManager().getBackStackEntryCount() > 0)
                    onBackPressed();
                else
                    drawerLayout.openDrawer(navigationView);
                return  true;
            }

            return super.onOptionsItemSelected(item);
        }
Hamza Mehmood
  • 151
  • 1
  • 10
0

Here is one more thing to check for in case the other answers here (or here or here or here) don't work.

I had copied some code from another activity that disabled the menu. Deleting this method (and applying the solutions given in the others answers) allowed the up button to work.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // hide the menu
    return false;
}
Community
  • 1
  • 1
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
0

In my case I had overridden the onCreateOptionsMenu method and I forgot to call super at the end.

Matt Mendrala
  • 211
  • 2
  • 3
0

Tool bar enable back button for Kotlin binding

setSupportActionBar(binding.toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_times_ic)
Ole Pannier
  • 3,208
  • 9
  • 22
  • 33