Zeta
Zeta

Reputation: 43

Include layout in view programmatically within a fragment

Alright so I have a fragment and I'd like to include, within its' xml file another layout which is programmatically inflated

Fragment:

public class zGoal_Fragment extends Fragment{

    private LinearLayout todayView;
    private View view;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.main_goal_view, container, false);
        todayView = (LinearLayout)view.findViewById(R.id.todayView);

        return view;
    }
}

xml's file for fragment:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="fill_parent"
          android:id="@+id/todayView"
>
</LinearLayout>

and xml layout I want included within the above xml programmatically:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/goalEditLayout"
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="100dp"
          android:background="@color/test_color_two"
>
</LinearLayout>

I've tried a couple different methods all of which led to " on a null object reference" errors...

plz help :))

Upvotes: 4

Views: 7113

Answers (2)

Drez
Drez

Reputation: 498

Have you tried something like this:

LinearLayout child = getLayoutInflater().inflate(R.layout.goalEditLayout, null);
todayView.addView(child);

Edit: Inside onCreateView:

LinearLayout inflatedLayout = (LinearLayout) inflater.inflate(R.layout.goalEditLayout, todayView, true);

Upvotes: 0

Adithya Upadhya
Adithya Upadhya

Reputation: 2375

I suppose the solution which you are looking for are Android ViewStubs. These are dynamically inflated layouts.

For more information you could refer these :

How to use View Stub in android

https://developer.android.com/reference/android/view/ViewStub.html

However, if you don't wish to inflate one layout inside another during runtime, you could try this the include tag:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="fill_parent"
          android:id="@+id/todayView">

         <include layout="@layout/your_layout_file_name"/>
</LinearLayout>

Upvotes: 2

Related Questions