android - 以编程方式添加布局资源

标签 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 没有初始化或什么的。有没有人可以帮助我?

最佳答案

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

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

关于android - 以编程方式添加布局资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26736536/

相关文章:

java - Android - 返回时 ListView 为空

android - 菜单按钮在 map 应用程序的模拟器上不起作用

java - str 的内容作为数组的名称

Android 设计支持库 TabLayout 使用自定义选项卡布局但布局包装选项卡

android - 使用两行不同的字体创建微调器下拉菜单

android - 为什么不可见的 LinearLayout 会占用空间?

android - LinearLayout 中的 fill_parent 没有得到尊重

android - PocketCasts 如何实现这种转换/效果?

Android Webview 无法加载 CSS 并显示 blockquote 字体颜色效果

javascript - 来自 Android 和 IOS 客户端的 Ratchet 套接字