在使用SlidingTabLayout 測試實作ViewPager頁卡滑動效果時,出現一個bug,經過一番百度查詢,發現問題是LayoutInflater.inflate()使用
就總結了一下inflate()的使用注意點。
inflate(int resource, ViewGroup root, boolean attachToRoot)
第一個參數 resource:布局檔案的id;
第二個參數 root:可選參數,布局檔案resource參數設定的參照物就是這個root,也就是說inflate方法會根據root的大小,将布局檔案
resource參數轉換成LayoutParam對象;
第三個參數官方解釋:是否将source布局添加到root中;
如果 inflate(resource,root);
inflate裡面把ViewGroup傳進去了,因為每一個View隻能有一個父view即parentView。當container不為空時,比如此fragment所待在的activity的
layout。而onCreateView中傳回的view是給ViewPager使用的,是以就會出現這個view有兩個parentView-即activity的layout和viewPager,是以會報出異常。
隻要如下解決即可:
1,infalte的時候把ViewGroup參數設定為null,view的parentView是ViewPager,ViewPager的parentView是activity的layout。
2,infalte設定參數為false。
如果 inflate(resource, null);
就等同于忽略了XML中的layout_width,layout_height
如果 inflate(resource, root, true);
那就會根據root生成一個布局檔案resource的LayoutParam對象,并将這個resource添加到root中