I'm trying to use .addView
to add another LinearLayout
to the ViewGroup
.
I am getting the following error on LogCat:
05-21 16:23:04.096: E/AndroidRuntime(2086): FATAL EXCEPTION: main 05-21 16:23:04.096: E/AndroidRuntime(2086): java.lang.NullPointerException 05-21 16:23:04.096: E/AndroidRuntime(2086): at android.view.ViewGroup.addView(ViewGroup.java:3148) 05-21 16:23:04.096: E/AndroidRuntime(2086): at android.view.ViewGroup.addView(ViewGroup.java:3131)
This is the code being called:
final LinearLayout eventContainerSub =
(LinearLayout) findViewById(R.layout.event_container);
final LinearLayout eventContainer =
(LinearLayout) findViewById(R.id.eventContainer);
eventContainer.addView(eventContainerSub);
Here is the ViewGroup
(the first linear layout):
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true"
android:id="@+id/eventContainer"
android:weightSum="100"
android:duplicateParentState="true">
And this is the (second) LinearLayout
I'm adding to the (first one) LinearLayout
above:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/eventContainerSub">
Both containers have the exact same name..eventContainerSub.
There is no eventContainer, change the view group to be the container as you planned..
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true"
android:id="@+id/event_container"
android:weightSum="100"
android:duplicateParentState="true">
and make sure the code is asking for the right Ids:
final LinearLayout eventContainerSub = (LinearLayout) findViewById(R.layout.eventContainerSub);
final LinearLayout eventContainer =
(LinearLayout) findViewById(R.id.event_container);
I'd also suggest you first remove the SubContainer from the view if it got inflated, as that view already has a parent and you cannot attach the SubContainer to two parents.
Either leave the subcontainer from this file and create a new one, or remove from the parent and only then add to the ViewGroup you want.
Android layout replacing a view with another view on run time