<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;
}
結果報錯如下:
總之就是說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生命週期注意啊。