Zeta Zeta - 1 month ago 25
Java Question

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"


>



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"


>



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

plz help :))

Answer

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