關於viewpager 裡嵌套 listview 同時實現翻頁功能的“java.lang.IllegalStateException: The specified child..."異常處理

來源:互聯網
上載者:User

     這幾天做項目用到了ViewPager,因為它可以實現左右划動多個頁面的效果,然後

再每個頁面裡使用ListView,運行時總是出現”PagerAdapter java.lang.IllegalStateException:

The specified child already has a parent. You must call removeView() ..."造成程式結束。

  調試時顯示在PagerAdapter適配器的:

@Override
public Object instantiateItem(ViewGroup container, int position)
{
   container.addView(views.get(position));
   return views.get(position);
}

 紅色代碼錯誤。很難理解新添加進來的view會自動綁定一個父類,由於一個兒子view不能與兩個父類相關,所以

必得解除綁定。

      在網上搜了很多解決辦法大多是用mViewPager.setOffscreenPageLimit(views.size()); 這種方法不用判斷

parent是不是已經存在,但多餘的listview還是不能被destroy。

下來貼下我解決問題的辦法,希望兄弟們不用困擾:

@Override
public Object instantiateItem(ViewGroup container, int position)
{
   try{
    if(views.get(position).getParent()==null){
              container.addView(views.get(position));
    }else{
               ((ViewGroup)views.get(position).getParent()).removeView(views.get(position));
               container.addView(views.get(position));
            }
    }catch(Exception e){
       e.printStackTrace();
    }
    return views.get(position);
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.