是否建议拨打onDetach()&手动使用FragmentTransaction的onAttach()方法

时间:2015-05-12 05:35:51

标签: android android-fragments android-activity

我想更改整个应用程序的字体大小。我使用了3种样式(小,中,大),将app主题保留为父级。每当用户根据所选样式选择字体更改按钮时,我都会更改整个应用程序的字体大小。因为,对于片段,必须在onCreateView()内部应用主题,在给布局充气之前,在单击字体大小更改按钮时不会将主题应用于片段。我需要刷新片段,以便重新创建它的视图。我手动分离片段,然后再次附加到活动。这会破坏片段视图并重新创建它,并更新片段UI。我的查询是,建议调用onDetach()& onAttach()手动? 这就是我刷新片段的方式:

private void reloadFragment() {
        android.support.v4.app.FragmentManager mngr = getSupportFragmentManager();
        Fragment fragment = mngr.findFragmentById(R.id.container);
        if (fragment instanceof HomeFragment) {
            try {
                SectionPagerAdapter adapter = ((HomeFragment) fragment).getAdapter();
                android.support.v4.app.FragmentTransaction transaction = this.getSupportFragmentManager().beginTransaction();
                transaction.detach(fragment).commitAllowingStateLoss();
                transaction.attach(fragment);
                adapter.notifyDataSetChanged();//I'm using viewpager, so notifying it
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
        }


    }

提前致谢..

1 个答案:

答案 0 :(得分:1)

不,你可以这样做。无法手动调用所有生命周期方法。如果您想更改Fragment,则需要执行以下操作:

private void reloadFragment() {
    android.support.v4.app.FragmentManager mngr = getSupportFragmentManager();
    Fragment fragment = mngr.findFragmentByTag(tag);
    if (fragment == null){
        fragment = new YourFragment();
    }
    if (fragment instanceof HomeFragment) {
        try {
            SectionPagerAdapter adapter = ((HomeFragment) fragment).getAdapter();
            android.support.v4.app.FragmentTransaction transaction = this.getSupportFragmentManager().beginTransaction();
            transaction.replace(resId, fragment, tag);
            adapter.notifyDataSetChanged();//I'm using viewpager, so notifying it
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }
}