Android Fragment错误膨胀类片段

时间:2016-09-23 09:47:05

标签: java android xml android-fragments

我在Android上正在做一个应用程序,我正在尝试设置一些片段,但每次启动应用程序时都会崩溃并出现两个错误:

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

MainActivity@ca3678d must implement OnFragmentInteractionListener

搜索互联网我发现很多人修复了他们从android :: name太类改变XML文件。我做到了,但仍然发生在我身上。

我使用此代码导航到片段:

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>

我在activity_main中实现它:

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

我该如何解决? 感谢

1 个答案:

答案 0 :(得分:0)

您尝试混合静态和动态Fragment用法。当您在布局中包含<fragment>元素时,您告诉系统要对类com.onelio.app.SearchFragment进行充气并将其插入布局中。 无法动态改变

当你创建一个新片段时(通过调用新的SearchFragment(),或者更好的是静态方法SearchFragment.createInstance()),你创建了一个动态片段,可以添加通过拥有FragmentTransaction(或其他Activity)布局中的Fragment视图

有关Fragment用法的详细信息和示例代码,请参阅this page