简体   繁体   中英

Android Fragment error inflating class fragment

I'm doing an app in Android and I'm trying to set some fragments but every time I launch the app it crash with two errors:

MainActivity: android.view.InflateException: Binary XML file line #25: Binary XML file line #25: Error inflating class fragment

MainActivity@ca3678d must implement OnFragmentInteractionListener

Searching for the internet I found a lot of people that fixed them changing the XML file from android::name too class. I did it and still happens to me.

I use this code to navigate into the fragment:

public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        Fragment fragment = new Fragment();

        if (id == R.id.nav_camera) {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.search_fragment, fragment);
            ft.commit();
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

My Fragment XML:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SearchFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment" />

</FrameLayout>

And I implement it in the activity_main:

<fragment android:id="@+id/search_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.onelio.app.SearchFragment"/>

How can I fix it? Thanks

You're trying to mix static and dynamic Fragment usage. When you include a <fragment> element in your layout you are telling the system to inflate the class com.onelio.app.SearchFragment and insert it into the layout. It cannot be changed dyanmically .

When you create a new fragment (via a call to new SearchFragment() , or better yet a static method SearchFragment.createInstance() ) you are creating a dynamic fragment which can be added via a FragmentTransaction to a view within the owning Activity (or other Fragment ) layout.

See this page for more details and example code on Fragment usage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM