从另一个XML加载布局

时间:2015-11-05 17:48:04

标签: android xml layout

我想更改“RelativeLayout”的内容,问题是该布局的内容是另一个xml。

setContentView(R.layout.activity_fullscreen);

//from actual xml
RelativeLayout rL1=  (RelativeLayout) findViewById(R.id.principalLayout); 

//from another xml 
RelativeLayout rL2=  (RelativeLayout) findViewById(R.id.cocinaL); 

rL1.removeAllViews();
rL1.addView(rL2); //this fail because rL2 is null

感谢

2 个答案:

答案 0 :(得分:1)

  

您无法添加另一个没有LayoutInflater的布局视图

    setContentView(R.layout.activity_fullscreen);


    //your actule view
    RelativeLayout rL1=  (RelativeLayout) findViewById(R.id.principalLayout); 

  LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);     
    //  your second xml
    View  view2 = inflater.inflate(R.layout.myview12, null);

    // add second View  
    rL1.addView(view2 );

答案 1 :(得分:0)

//来自实际的xml

  RelativeLayout rL1= (RelativeLayout) findViewById(R.id.principalLayout); 

//来自另一个xml

 View child = getLayoutInflater().inflate(R.layout.child, null);
 RelativeLayout rL2 =  (RelativeLayout) child.findViewById(R.id.cocinaL); 
 rL1.removeAllViews();
 rL1.addView(rL2);