完成片段与它的主机活动整体

时间:2015-12-18 01:57:40

标签: android android-fragments android-activity fragment lifecycle

当我必须完成一个只有一个片段的活动时,我注意到片段在空白活动(容器活动)完成之前消失了。

你们如何处理这种情况?

SingleFragmentActivity.java:

    public class SingleFragmentActivity extends BaseSecondaryActivity{

        public static final java.lang.String FRAGMENT_CLASS_NAME = "fragment_class_name";
        public static final java.lang.String FRAGMENT_TITLE = "fragment_title";
        private String title;
        private ActionBarFragment fragment;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Bundle bundle = getIntent().getExtras();
            String fragmentName = bundle.getString(FRAGMENT_CLASS_NAME);
            if(bundle.getInt(FRAGMENT_TITLE) == 0){
                title = "";
            }else {
                title = getString(bundle.getInt(FRAGMENT_TITLE));
            }
            try {
                FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                Class<ActionBarFragment> fragmentClass  = (Class<ActionBarFragment>) Class.forName(fragmentName);
                fragment = fragmentClass.newInstance();
                bundle.remove(FRAGMENT_TITLE);
                bundle.remove(FRAGMENT_CLASS_NAME);
                fragment.setArguments(bundle);
                fragmentTransaction.replace(R.id.fragment_container, fragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        @Override
        protected int provideContentViewId() {
            return R.layout.activity_with_fragment;
        }

        protected String getActionBarTitleString() {
            return title;
        }
    }

activity_with_fragment.xml

     <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/action_bar" />

        <FrameLayout
            android:id="@+id/fragment_container"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"/>

    </LinearLayout>

0 个答案:

没有答案