Can't inflate layout properly for a fragment in Android application

android, fragment, layout-inflater, textview

Solution

You should pass `container` as a parent.

FragmentView = inflater.inflate(
            R.layout.tasks, 
            container,
            false
        );

Also you should specify `false`, so `LayoutInflater` does not attach the inflated view to parent. The inflated view is attached to parent by `FragmentManager`.

Problem

In first place this is the code of the fragment: ``` public class MyFragment extends Fragment { private View FragmentView; public static Fragment newInstance() { MyFragment NewFragment = new MyFragment(); return NewFragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { FragmentView = inflater.inflate( R.layout.tasks, new LinearLayout(MainActivity.MainContext) ); FragmentView.setLayoutParams( new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT ) ); addText(); return FragmentView; } private void addText() { TasksView.setBackgroundResource(R.drawable.bg_image); TextView MyTitle = new TextView(MainActivity.MainContext); MyTitle.setLayoutParams( new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT ) ); MyTitle.setText(R.string.mytitle); ((LinearLayout) FragmentView).addView(MyTitle ); } } ``` `MainActivity.MainContext` is stored as `public static` in the main activity's class and is retrieved when creating the activity by `getApplicationContext()`. Now, the problem lays here: ``` FragmentView = inflater.inflate( R.layout.tasks, new LinearLayout(MainActivity.MainContext) ); ``` Because of this, the `MyTitle` text view is not displayed inside the fragment. If I do this: ``` FragmentView = inflater.inflate(R.layout.tasks, null); ``` it is displayed but I get a warning: ``` Avoid passing null as the view root (needed to resolve layout parameters on the inflated layout's root element) ``` I would like do it properly and not get any warnings and I don't find a way. I also tried: ``` FragmentView = inflater.inflate(R.layout.tasks, container); ``` but the application crashes.

Original source