3

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?

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

Comments

2

you need to inflate the debugLayout with the LayoutInflater

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.