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);
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容