How to go back to previous fragment from activity?

前端 未结 8 1385
太阳男子
太阳男子 2021-02-07 08:26

I\'ve got an app with nav drawer, which is switching fragments. From inside one of those fragments, I am calling a new activity. When I click back in this activity (in toolbar),

相关标签:
8条回答
  • 2021-02-07 08:44

    Sorry, I don't have enough reputation to leave a comment. So I have to guess. I once had the same issue. Sounds like a problem related to the activity lifecycle (http://developer.android.com/reference/android/app/Activity.html#ProcessLifecycle). Be sure to add your first fragment only once, because your activity's fragment manager is capable of the lifecycle. Thus, the statement that adds the first fragment to your fragment manager should be surrounded by if (savedInstanceState == null) { ... }.

    0 讨论(0)
  • 2021-02-07 08:49

    I had the same problem and got fixed. The only thing you need to do is to override the method "onOptionsItemSelected" in the activity:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    

    android.R.id.home is your first fragment in the menu.

    0 讨论(0)
  • 2021-02-07 08:50

    Try

    getFragmentManager().popBackStackImmediate();
    

    It worked for me.

    0 讨论(0)
  • 2021-02-07 08:51

    Override onOptionsItemSelected method in activity as follows,

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }
    
    0 讨论(0)
  • 2021-02-07 08:57

    When you call new Activity from Fragment you should write :

    Intent intent = new Intent(getFragment().getContext(),NewActivity.class);
    getFragment().getContext().startActivity(intent);
    
    FragmentManager fm = CurrentFragment.getActivity().getSupportFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    ft.addToBackStack(CurrentFragment.class.getName()).commit();
    fm.executePendingTransactions();
    

    It Works for me.

    0 讨论(0)
  • 2021-02-07 09:04

    When you call an activity from other activity's fragment, then the previous activity's instance state that is the calling activity which was having fragment's instance state will be saved in stack...so all u need to do is finish the called activity and u will have the fragment from which you called your second activity.

    @Override
    public void onBackPressed() {
    finish();
    }
    
    0 讨论(0)
提交回复
热议问题