LayoutInflater.inflate 中的坑

public View inflate(int resource, ViewGroup root, boolean attachToRoot)

參數(shù)解釋:
1.resource --> xml 資源的ID,例如R.layout.activity_main;
2.root --> 該參數(shù)可選,如果attachToRoot為true的情況下,root會作為resource的的父視圖.
3.attachToRoot resource資源是否需要裝載到root中.

package com.test.app;

/**
 * 測試
 * Created by fengwenhua on 2017/5/23.
 */

public class TestActivity extends AppCompatActivity {

    @BindView(R.id.splash_rl_content)
    public LinearLayout splash_rl_content;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        ButterKnife.bind(this);

//        testLayoutInflater();
        testChildViewHeight();

        testChildViewHeightNormal();
    }


    /**
     * 以下代碼將導致系統(tǒng)崩潰
     * inflate(R.layout.activity_splash,splash_rl_content,true)
     * 究其原因,在attachToRoot為true且root不為空的情況下,view 已經(jīng)被添加到root中,已經(jīng)存在父視圖
     */
    public void testLayoutInflater(){
        View view = getLayoutInflater().inflate(R.layout.item_test,splash_rl_content,true);
        // 以下代碼將導致如下異常,并導致系統(tǒng)崩潰
        // java.lang.IllegalStateException: The specified child already has a parent.
        // You must call removeView() on the child's parent first.
        splash_rl_content.addView(view);//問題點
    }

    /**
     * 以下代碼會導致item_test的寬高不起作用
     */
    public void testChildViewHeight(){
        View view = getLayoutInflater().inflate(R.layout.item_test,null);
        splash_rl_content.addView(view);
    }

    /**
     * 以下代碼會導致item_test的寬高不起作用
     */
    public void testChildViewHeightNormal(){
        View view = getLayoutInflater().inflate(R.layout.item_test,splash_rl_content,true);
//        splash_rl_content.addView(view);
    }
}

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容