简体   繁体   中英

Navigate back from an Activity to fragment of another Activity

I have an activity(Activity1) with several fragments. I'm calling a second activity(Activity2) from one of the fragments(say Fragment C) of first Activity. I want to navigate back from the second activity(Activity2) to Fragment C. But, it is navigating to the first fragment of Activity1 instead of Fragment C. Please help.

Block of code I have tried so far:

In Fragment C,

categoryButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            Intent i=new Intent(getActivity(),Activity2.class);
            getActivity().startActivity(i);
        }
    });

In the container Activity ie Activity1,

FragmentTransaction transaction= getSupportFragmentManager().beginTransaction();

        FragmentC myFragment = new FragmentC();

        transaction.replace(R.id.frame_container, myFragment);

        transaction.commit();

According to the Official Android Documentation the best way to have Fragment to communicate with another even to another Activity is through the associated Activity.

To avoid any mess with Fragment Transaction please referring to this:

Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM