android fragment嵌套fragment出现的问题:no activity

package com.example.fragmentNavigation2.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.fragmentNavigation2.R;
import com.viewpagerindicator.TabPageIndicator;

import java.lang.reflect.Field;

public class AddressFragment extends Fragment {

    private static final String[] CONTENT = new String[]{"协会简介", "矿业新闻", "活动与交流", "会员中心"};
    private FragmentManager fragmentManager;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        fragmentManager = getChildFragmentManager();
        final Context contextThemeWrapper = new ContextThemeWrapper(getActivity(), com.viewpagerindicator.R.style.Theme_PageIndicatorDefaults);
        // clone the inflater using the ContextThemeWrapper
        LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper);
        View view = localInflater.inflate(R.layout.simple_tabs, container, false);

        FragmentPagerAdapter adapter = new FragmentPagerAdapter(fragmentManager) {

            @Override
            public Fragment getItem(int position) {
                return TestFragment.newInstance(CONTENT[position % CONTENT.length]);
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return CONTENT[position % CONTENT.length].toUpperCase();
            }

            @Override
            public int getCount() {
                return CONTENT.length;
            }
        };

        ViewPager pager = (ViewPager) view.findViewById(R.id.pager);
        pager.setAdapter(adapter);

        TabPageIndicator indicator = (TabPageIndicator) view.findViewById(R.id.indicator);
        indicator.setViewPager(pager);
        indicator.setFillViewport(true);
        return view;
    }

    /**
     * 这段可以解决fragment嵌套fragment会崩溃的问题
     */
    @Override
    public void onDetach() {
        super.onDetach();
        try {
            //参数是固定写法
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}

解决方案为红色部分,获取fragmentManager时要用getChildFragmentManager()这个方法。

还要重写onDetach方法,照着红色部分写。

posted @ 2014-01-18 00:45  无忧之路  阅读(3647)  评论(0编辑  收藏  举报
无忧之路