Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add layout resource programmatically

I have a custom layout called "debug.xml" in folder "layout/" which is desired to add programmatically into a predefined Layout in activity_main.xml called centerLayout. The "debug.xml" is something like:

<?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>

I want to add this "debug_layout" into a centerLayout:

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

But it encounters NULL pointer excetion at "centerLayout.addView(debugLayout);". So it seems the debug_layout is not initialized or something. Does anyone can help me?

like image 569
William Lai Avatar asked Dec 10 '25 05:12

William Lai


2 Answers

Are you sure that your centerLayout is not null? If not, did you tried?:

LinearLayout centerLayout = (LinearLayout) findViewById (R.id.center_layout);
LinearLayout debugLayout = getLayoutInflater().inflate(R.layout.debug, centerLayout, false);
centerLayout.addView(debugLayout);
like image 155
Hellboy Avatar answered Dec 12 '25 19:12

Hellboy


you need to inflate the debugLayout with the LayoutInflater

like image 29
ligi Avatar answered Dec 12 '25 18:12

ligi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!