Android Fragment 嵌套使用报错

http://www.android100.org/html/201406/03/16248.html

在新的SDK每次创建activity时,会自动生成

public static class PlaceholderFragment extends Fragment

fragment模块,在该模块的基础上进行嵌套fragment代码如下:

public static class PlaceholderFragment extends Fragment {

		static FragmentManager fm;
		public PlaceholderFragment() {		
   			fm=getChildFragmentManager();
		}
		@Override  
		public void onCreate(Bundle savedInstanceState) {  
		    super.onCreate(savedInstanceState);  	
		 
	    }  
		
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView=LayoutInflater.from(getActivity())
					.inflate(R.layout.tab, null);
			
			if(fm.findFragmentByTag("haha")==null)
			{
				Fragment1 f1=new Fragment1();
				fm.beginTransaction().add(R.id.frame_tab,f1,"haha").commit();
			}
			return rootView;
		}

结果报错如下:

总之就是说Acitivity被被销毁了。

原因:

fm=getChildFragmentManager();在 PlaceholderFragment 的构造函数中调用,此时它还没有创建onCreate,自然获取不到Fragment及activity了,因此将其写入
public void onCreate(Bundle savedInstanceState) {  
		    super.onCreate(savedInstanceState);  		 
			fm=getChildFragmentManager();
	    }  
错误解决,大家一定要对Fragment及activity生命周期注意啊。
原文地址:https://www.cnblogs.com/leiqun123/p/4547846.html