以编程方式添加布局资源

时间:2014-11-04 13:38:37

标签: android android-layout

我在“layout /”文件夹中有一个名为“debug.xml”的自定义布局,希望以编程方式添加到activity_main.xml中名为centerLayout的预定义布局中。 “debug.xml”类似于:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/debug_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <EditText
            android:id="@+id/commandEditText"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:gravity="center_vertical"
            android:inputType="text" />
    </LinearLayout>

</LinearLayout>

我想将此“debug_layout”添加到centerLayout:

LinearLayout centerLayout = (LinearLayout) findViewById (R.id.center_layout);
LinearLayout debugLayout = (LinearLayout) findViewById (R.id.debug_layout);
centerLayout.addView(debugLayout);

但它在“centerLayout.addView(debugLayout);”遇到NULL指针。所以似乎debug_layout没有初始化或者其他东西。有人可以帮助我吗?

2 个答案:

答案 0 :(得分:2)

您需要使用LayoutInflater

来扩充debugLayout

答案 1 :(得分:1)

您确定您的centerLayout不为空吗?如果没有,你试过吗?:

LinearLayout centerLayout = (LinearLayout) findViewById (R.id.center_layout);
LinearLayout debugLayout = getLayoutInflater().inflate(R.layout.debug, centerLayout, false);
centerLayout.addView(debugLayout);
相关问题