2014-11-04 46 views
1

我在文件夹“layout /”中有一个名为“debug.xml”的自定义布局,它需要以编程方式添加到名为centerLayout的activity_main.xml中的预定义布局中。该 “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指针EXCETION ;”。所以看来debug_layout没有被初始化或者什么。有人可以帮助我吗?

回答

1

你确定你的centerLayout不为空吹大debugLayout?如果没有,您是否尝试过?:

LinearLayout centerLayout = (LinearLayout) findViewById (R.id.center_layout); 
LinearLayout debugLayout = getLayoutInflater().inflate(R.layout.debug, centerLayout, false); 
centerLayout.addView(debugLayout); 
2

您需要使用LayoutInflater

相关问题