gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 15:58:04 25 4
gpt4 key购买 nike

我在文件夹“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com