2016-09-23 72 views
-3

我在做Android的應用程序,我想設置一些片段,但我每次啓動應用時它有兩個錯誤崩潰:Android的碎片誤差充氣類片段

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

[email protected] must implement OnFragmentInteractionListener

搜索互聯網,我發現了很多的固定他們的Android ::名字太類改變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; 
    } 

我的片段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"/> 

哪有我修理它? 感謝

回答

0

你試圖混合靜態和動態Fragment使用。當您在您的佈局<fragment>元素,你是在告訴系統充氣類com.onelio.app.SearchFragment並將其插入到佈局。 它不能dyanmically改變。

當創建一個新的片段(通過新SearchFragment(),或更好的呼叫又一個靜態方法SearchFragment.createInstance())要創建,其可通過FragmentTransaction視圖加入內所屬Activity一個動態片段(或其它Fragment)佈局。

的更多細節和示例代碼上Fragment用法請參見this page