2

我需要在运行时根据单击按钮向我的活动动态添加“模板”布局。

下面的代码块中显示的是我的布局的简化版本。HEADER C的内容(即BODY C1, BODY C2 ... BODY Cn)是运行时需要添加的组件。它们都具有相同的格式,并在具有相对布局的单独 xml 文件中定义。我如何完成这项任务?我尝试了 LayoutInflater,但没有成功。LayoutInflater 是否需要 LinearLayout 才能充气?

<SCROLLVIEW>
   <RELATIVE_LAYOUT>
      ____________
      HEADER A
         ____________
         BODY A
   </RELATIVE_LAYOUT>
   <RELATIVE_LAYOUT>
      ____________
      HEADER B
       ____________
    BODY B
</RELATIVE_LAYOUT>
<RELATIVE_LAYOUT>
____________
HEADER C
    ____________
    BODY C1
    ____________
    BODY C2
    .
    .
    .
    ____________
    BODY Cn
<RELATIVE_LAYOUT>
</SCROLLVIEW>

谢谢,任何指导表示赞赏!

4

4 回答 4

1

采用

View headerView = View.inflate(this, R.layout.class_name, null);

膨胀你的布局。

于 2012-05-03T04:30:28.073 回答
1
/**rootView represent the RelativeLayout*/
View headerView = LayoutInflater.from(context).inflater(R.layout.header_view, rootView, false);
rootView.add(headerView);
于 2012-05-03T04:32:51.360 回答
1

你可以这样做:

general = (LinearLayout) findViewById(R.id.general_tab);  // get the id of the layout you wish to add your view to
TextView programs = new TextView(this); // create a new view/widget to add
programs.setText("Program(s): " + prgdisp);  // set the text 
general.addView(programs);  // add the new view/widget to the existing layout

编辑

我错过了你已经有一个 xml 布局。将以上内容更改为:

general = (LinearLayout) findViewById(R.id.general_tab);  // get the id of the layout you wish to add your view to
View header = View.inflate(this, R.layout.class_name, null); // inflate your layout
general.addView(header);  // add the new view/widget to the existing layout
于 2012-05-03T04:34:03.410 回答
1
    LinearLayout Parent = (LinearLayout) findViewById(R.id.linearLayout);

    View child = getLayoutInflater().inflate(R.layout.main_new,null);
    Parent.addView(child);
于 2012-05-03T04:37:39.953 回答