Search code examples
androidandroid-fragmentsonbackpressed

back from fragment 2 to fragment 1 but title still that from fragment 2


Every one i have a problem and can't figure how to solve it;

the problem is i has mainActivity that contain toolbar is it's xml and in onCreate() i add fragment 1 with this code

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

        try {
            // put the fragment to the Main Activity
            mainFragment = (MainFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container);
            if (mainFragment == null) {
                mainFragment = MainFragment.newInstance();
                getSupportFragmentManager()
                        .beginTransaction()
                        .add(R.id.fragment_container, mainFragment)
                        .commit();
            }
        } catch (Exception e) {
            goToMainFragment();
            //   Log.v("goToMainFragment()", "goToMainFragment()");
        }
    }

then i had button for example or from drawer when click on it go to fragment 2 with this code

public void editTimeSheet() {
    AddTimeSheetFragment timeSheetFragment = new AddTimeSheetFragment();
    Bundle bundle = new Bundle();
    bundle.putInt("action", 2);
    bundle.putSerializable("timeSheet", timeSheet);
    timeSheetFragment.setArguments(bundle);

   getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, timeSheetFragment).addToBackStack("stack").commit();

}

and of course in each fragment i change toolbar title using getActivity().setTitle("some title");

but the problem is when i back using onBackPressed the title not change and still the title that set from fragment 2 , I know why because i change the toolbar title of the activity and when i back to fragment 1 onCreateView not called so the title not changed , i try call fragment lifeCycle methods so any method has called in the back button i will change toolbar title from it but seems no method has call when back

i'm sorry if the question not clear enough but it's the best i write it and describe the problem, thanks for your time


Solution

  • ok nobody answer me and after long time of research i found this and it's work

    @Override
        public void onHiddenChanged(boolean hidden) {
            super.onHiddenChanged(hidden);
            if (hidden) {
    //            Toast.makeText(getContext(), "hide fragment", Toast.LENGTH_SHORT).show();
            } else {
    //            Toast.makeText(getContext(), "show fragment", Toast.LENGTH_SHORT).show();
                setToolbarTitle();
            }
        }
    

    after back to fragment 1 this method is called with hidden value = false