Android Fragment 嵌套使用报错

时间:2014-05-15 23:19:23   收藏:0   阅读:461
在新的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;
		}


结果报错如下:

bubuko.com,布布扣

总之就是说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

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!