Android - Fragment 2使用Activity显示主片段

时间:2013-07-23 09:16:29

标签: java android android-fragments

从主要片段我打开VideoPlayerFragment,在VideoPlayerFragment中,当我按下一个按钮时,它应该返回到父片段。

CollectionDemoActivity{

class LaunchpadSectionFragment extends ListFragments{

public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

String fragMainGroups = "mainGroups";


                    Fragment fragment1 = new VideoPlayerFragment();

                    FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
                    transaction.replace(R.id.contentFragment, fragment1, fragMainGroups );
                    transaction.addToBackStack(fragMainGroups);
                    transaction.commit(); 

      }
   }
}

外部课程

VideoPlayerFragment.java

类VideoPlayerFragment扩展了ListFragment {

            @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState) {

                            String Groups = "Groups";

                            Fragment fragment1 = new CollectionDemoActivity.LaunchpadSectionFragment();

                            FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
                            transaction.replace(R.layout.load_main_groups_activty, fragment1, Groups);
                            transaction.addToBackStack(Groups);
                            transaction.commit(); 

             }

}

1 个答案:

答案 0 :(得分:0)

我必须使用下面的代码,使用其片段标记从backstack打开上一个片段。

String fragMainGroups = "mainGroups";
                            String Groups = "Groups";

                            Fragment fragment = (Fragment) getFragmentManager().findFragmentByTag(fragMainGroups);                                              


                            if (fragment != null) // could be null if not instantiated yet
                            {
                                if (fragment.getView() != null) {
                                    // Pop the backstack on the ChildManager if there is any. If not, close this activity as normal.
                                    if (!fragment.getFragmentManager().popBackStackImmediate()) {
                                        fragment.getFragmentManager().popBackStack();
                                        //getActivity().finish();
                                    }
                                }
                            }