LayoutInflater.inflate 中的坑

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

参数解释:
1.resource --> xml 资源的ID,例如R.layout.activity_main;
2.root --> 该参数可选,如果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();
    }


    /**
     * 以下代码将导致系统崩溃
     * inflate(R.layout.activity_splash,splash_rl_content,true)
     * 究其原因,在attachToRoot为true且root不为空的情况下,view 已经被添加到root中,已经存在父视图
     */
    public void testLayoutInflater(){
        View view = getLayoutInflater().inflate(R.layout.item_test,splash_rl_content,true);
        // 以下代码将导致如下异常,并导致系统崩溃
        // 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);
    }
}

你可能感兴趣的:(LayoutInflater.inflate 中的坑)