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

来源:互联网 发布:ios仿淘宝商品详情 编辑:程序博客网 时间:2024/06/09 16:17

出错代码:

<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;@Overridepublic 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  }


当在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();//所有的控件 都有爹  爹一般情况下 就是ViewGoupif(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复用

0 0
原创粉丝点击