将外部xml视图添加到当前视图

时间:2012-11-02 07:17:30

标签: android android-layout android-view

我已经创建了一个表单( form.xml ):

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/formLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >
    <TextView
        android:id="@+id/tvName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android :text="Name" />

    <EditText
        android:id="@+id/edName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

<!-- Many more things-->
</RelativeLayout>

如果上面的表单是通过代码创建的(比如FormView),那么在每个活动中我都可以使用类似

的内容
<com.example.FormView
    android:id="@+id/fv1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

但由于表格是使用xml创建的,如上所示,我如何在众多活动中使用它? 我希望在所有活动中使用上面的表单布局(form.xml)作为用户控件。


我尝试过关注,但它会在最后一行抛出NullPointerException

setContentView(R.layout.main);
RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.container);
View form= (View) findViewById(R.id.formLayout);
mainLayout.addView(form);

任何建议都表示赞赏。

2 个答案:

答案 0 :(得分:1)

请看这里Re-using layouts

它显示了如何重复使用现有布局以将其包含在其他布局中。

答案 1 :(得分:-1)

你到底想要做什么,然后我会为你编写代码,使用下面的代码并将你的小部件放入其中并完成......

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.XMLFileName);