JACK GAO JACK GAO - 3 months ago 7
Android Question

Error inflating class fragment when I replace the fragment

I am new in android.
I want to replace a fragment by code.Here is my code.
MainActivity:

public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

setDefaultFragement();
}
private void setDefaultFragement() {
ContentFragment fragment = new ContentFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.fra_content,fragment).commit();
}
}


Here is my ContentFragment

public class ContentFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_content, container, false);
}
}


mylayout:

<fragment
android:id="@+id/fra_content"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@id/fra_title"
/>


However I got these error

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.administrator.myapplication/com.example.administrator.myapplication.MainActivity}: android.view.InflateException: Binary XML file line #13: Error inflating class fragmet

Answer

Rather than using "fragment" in your xml, use a FrameLayout. If you wish to use a fragment in your xml, it must be specified, thus having no need for fragment manager.

So, in your xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@id/toolbar"
    android:id="@+id/content"/>

In your activity:

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(enterAnimation, exitAnimation);
ft.replace(R.id.content, new ContentFragment());
ft.commit();

And in your fragment:

public class ContentFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_content, container, false);
    return rootView;
 }
}
Comments