动态创建UI

| 我想在代码中实现以下“ 0”:
<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>
谁能告诉我如何在代码中实现这一点。 提前感谢。
已邀请:
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);
您可以使用与布局xml文件相同的层次结构手动创建所有UI元素。 在Activity.onCreate()中说
onCreate(...) {
    super.onCreate(...);
    RelativeLayout layout = new RelativeLayout(...);
    Button button = new Button(...);
    layout.addView(button);
    setContentView(layout);
}

要回复问题请先登录注册