4

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 :))

ArK
  • 20,698
  • 67
  • 109
  • 136
Zeta
  • 43
  • 1
  • 5
  • I have added an answer for your query. You could either use ViewStubs or even better, use include tag and add your layout of another file inside the target xml file... – Adithya Upadhya Oct 30 '16 at 20:26

2 Answers2

2

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>
Community
  • 1
  • 1
Adithya Upadhya
  • 2,239
  • 20
  • 28
0

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);
Drez
  • 488
  • 3
  • 10
  • i may be wrong but getLayoutInflater() in a fragment cannot be called without a bundle parameter. :/ – Zeta Oct 30 '16 at 20:31