viewpager加载fragment出错Caused by: java.lang.IllegalStateException: The specified child already has a p

时间:2022-03-17 20:33:35

出错代码:

<style type="text/css">PRE.western { font-family: "文泉驿微米黑"; }PRE.cjk { font-family: "文泉驿微米黑"; }PRE.ctl { font-family: "Lohit Hindi",monospace; }P { margin-bottom: 0.21cm; }</style><pre class="cjk">public class HomeFragment extends Fragment {
public static final int STATE_UNKOWN = 0;
public static final int STATE_LOADING = 1;
public static final int STATE_ERROR = 2;
public static final int STATE_EMPTY = 3;
public static final int STATE_SUCCESS = 4;
public static int state = STATE_UNKOWN;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (frameLayout == null) { // 之前的frameLayout 已经记录了一个爹了 爹是之前的ViewPager
frameLayout = new FrameLayout(getActivity());
init(); // 在FrameLayout中 添加4种不同的界面
}
show();// 根据服务器的数据 切换状态
// 先干掉之前的爹

return frameLayout; // 拿到当前viewPager 添加这个framelayout
}

 

viewpager加载fragment出错Caused by: java.lang.IllegalStateException: The specified child already has a p

当在fragment3时,fragment1就被干掉,当画到fragment2时,就加载fragment1,这个时候上面代码里的framelayout不是空,

<pre class="cjk"> // 之前的frameLayout 已经记录了一个爹了  爹是之前的ViewPager 

这就要找到之前的parent,让parent 干掉framelayout 

public class ViewUtils {
public static void removeParent(View v){
// 先找到爹 在通过爹去移除孩子
ViewParent parent = v.getParent();
//所有的控件 都有爹 爹一般情况下 就是ViewGoup
if(parent instanceof ViewGroup){
ViewGroup group=(ViewGroup) parent;
group.removeView(v);
}
}
}

再给framelayout添加代码

         if (frameLayout == null) {  // 之前的frameLayout 已经记录了一个爹了  爹是之前的ViewPager 
frameLayout = new FrameLayout(getActivity());
init(); // 在FrameLayout中 添加4种不同的界面
         }else{
ViewUtils.removeParent(frameLayout);// 移除frameLayout之前的爹
         }

  这样就能进行framelayout复用