Android Fragment 嵌套使用报错

在新的SDK每次创建activity时,会自动生成 
<pre name="code" class="java">public static class PlaceholderFragment extends Fragment


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

<pre name="code" class="java">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;
		}

结果报错如下:

Android Fragment 嵌套使用报错

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

原因:

fm=getChildFragmentManager();在 <span style="font-family: Arial, Helvetica, sans-serif;">PlaceholderFragment 的构造函数中调用,此时它还没有创建onCreate,自然获取不到Fragment及activity了,因此将其写入</span>
<span style="font-family: Arial, Helvetica, sans-serif;"></span><pre name="code" class="java"><pre name="code" class="java">public void onCreate(Bundle savedInstanceState) {  
		    super.onCreate(savedInstanceState);  		 
			fm=getChildFragmentManager();
	    }  

错误解决,大家一定要对Fragment及activity生命周期注意啊。


Android Fragment 嵌套使用报错,布布扣,bubuko.com

Android Fragment 嵌套使用报错

上一篇:Android Run模式下提示"Waiting For Debugger"


下一篇:android intent ACTION大全