0

I'm starting to learn Android and am having a problem when creating fragments. I've tried creating a fragment in code in just about every way every tutorial specifies but every time I do the program immediately crashes and I get a log error "no view found for [id of fragment for container]".

The activity I create the fragment from is:

public class MainActivity extends FragmentActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();

    FragmentTestActivity activity = new FragmentTestActivity();
    ft.add(R.id.fragment_container, activity);
    ft.commit();
}


}

The fragment itself if

public class FragmentTestActivity extends Fragment {

public View onCreateView(LayoutInflater inflater, ViewGroup parent,
                         Bundle savedInstanceState) {
    View vw = inflater.inflate(R.layout.fragment, parent, false);
    return vw;
}
}

And the layout of the fragment is

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/fragment_container" >


</FrameLayout>  

It doesn't do anything useful at the moment, I just want to see if I can make a fragment before moving on to do anything useful, but every time I try the program crashes.

Ghost
  • 103
  • 4

3 Answers3

1

activity_main.xml must have a FrameLayout with id fragment_container.

Your FrameLayout is the container. You add the the fragment to the FrameLayout. Your fragment is hosted by a activity.

Also i don't think you require a FrameLayout in fragment layout. You can have other views for fragment layout.

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
0
ft.add(R.id.fragment_container, activity);

In this fragment_container needs to be in activity layout not fragment layout.

vipul mittal
  • 17,343
  • 3
  • 41
  • 44
0

By doing this

ft.add(R.id.fragment_container, activity);

you are trying to add your Fragment to a View inside the MainActivity that has an id of R.id.fragment_container. Since fragment_container if part of your Fragment's layout and not part of your MainActivity's layout, it causes your error.

Make sure you have a ViewGroup that has the id R.id.fragment_container inside your MainActivity layout and rename the main ViewGroup's id inside your Fragment layout.

2Dee
  • 8,609
  • 7
  • 42
  • 53