Android - 将布局添加到父布局

时间:2011-12-06 18:23:16

标签: android android-layout

我有2个布局xml文件:“highlight.xml”和“highlight_cell.xml”。

以下是每个版本的简化版本。我删除了宽度/高度/等,只保留了重要的属性......

highlights.xml

<LinearLayout>
  <uk.co.jasonfry.android.tools.ui.SwipeView android:id="@+id/swipe_view" />
  <uk.co.jasonfry.android.tools.ui.PageControl android:id="@+id/page_control" />
</LinearLayout>

highlights_cell.xml

<LinearLayout android:orientation="vertical">
  <LinearLayout android:id="@+id/linear_layout1" android:orientation="horizontal">
    <ImageView android:id="@+id/logo" />
    <LinearLayout android:id="@+id/linear_layout2" android:orientation="vertical">
      <TextView android:id="@+id/title" />
      <TextView android:id="@+id/subtitle" />
    </LinearLayout>
  </LinearLayout>

  <ScrollView android:id="@+id/scroll_view">
    <TextView android:id="@+id/description" />
  </ScrollView>
</LinearLayout>

我的想法是,我想通过循环将几个“highlight_cell”添加到“突出显示”。

我把一些测试代码扔到一起如下,但由于它不起作用,我怀疑我没有正确添加单元格布局,或者我不应该使用“inflater”......

/** Declare shared variables */
SwipeView mSwipeView;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState){

    //Initialise layout and variables
    super.onCreate(savedInstanceState);
    setContentView(R.layout.highlights);

    //Setup controls
    mSwipeView = (SwipeView) findViewById(R.id.swipe_view);

    LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);

    //Loop through collection and add views
    for(int i=0; i<7;i++)
    {
        //Create the itemView to use layout xml for each cell  
        View itemView = inflater.inflate(R.layout.highlights_cell, null);

        //Set values within cell
        TextView title = (TextView) itemView.findViewById(R.id.title);
        title.setText("HELLO WORLD_" + i);

        //add the itemView to main view
        mSwipeView.addView(itemView);
    }
}

这是将布局动态添加到父布局的正确方法吗? 谢谢!

1 个答案:

答案 0 :(得分:2)

除了一些东西外,它看起来不错。

由于您要向自定义ViewGroup添加视图,因此您必须确保它正确布局并显示其子项。

此外,当您向View添加ViewGroup时,您可以指定ViewGroup中视图可以包含的LayoutParams

有关创建自定义ViewGroup

的更多信息