2011-04-19 96 views
0

我要实现以下代码layout动态创建UI

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/widget92" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 

    <Button 
      android:id="@+id/widget164" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Button" 
      android:layout_alignTop="@+id/widget163" 
      android:layout_alignLeft="@+id/widget161" /> 

    <Button 
      android:id="@+id/widget163" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Button" 
      android:layout_alignTop="@+id/widget162" 
      android:layout_toLeftOf="@+id/widget161" /> 

    <Button 
      android:id="@+id/widget162" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Button" 
      android:layout_below="@+id/widget161" 
      android:layout_toLeftOf="@+id/widget160" /> 

    <Button 
      android:id="@+id/widget161" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Button" 
      android:layout_alignParentTop="true" 
      android:layout_toRightOf="@+id/widget160" /> 

    <Button 
      android:id="@+id/widget160" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Button" 
      android:layout_alignParentTop="true" 
      android:layout_toRightOf="@+id/widget159" /> 

    <Button 
      android:id="@+id/widget159" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Button" 
      android:layout_alignParentTop="true" 
      android:layout_alignParentLeft="true" /> 

</RelativeLayout> 

谁能告诉我如何实现这一代码。 Thanx提前。

回答

0
RelativeLayout rl = new RelativeLayout(this); 
     LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); 
     rl.setId(R.id.widget92); 

     Button btn = new Button(this); 
     btn.setId(R.id.widget164); 
     btn.setText("Text"); 
     lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
     lp.addRule(RelativeLayout.ALIGN_TOP, R.id.widget163); 
     lp.addRule(RelativeLayout.ALIGN_LEFT, R.id.widget161); 
     rl.addView(btn, lp); 

     btn = new Button(this); 
     lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
     ... 

     setContentView(rl); 
2

您可以使用与布局xml文件中相同的层次结构手动创建所有UI元素。

发言权Activity.onCreate()

onCreate(...) { 
    super.onCreate(...); 
    RelativeLayout layout = new RelativeLayout(...); 
    Button button = new Button(...); 
    layout.addView(button); 
    setContentView(layout); 
}