[英]Android Fragment error inflating class fragment
我正在 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 too class 更改 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"/>
我該如何解決? 謝謝
您正在嘗試混合使用靜態和動態Fragment
。 當您在布局中包含<fragment>
元素時,您是在告訴系統膨脹類com.onelio.app.SearchFragment
並將其插入到布局中。 它不能動態地改變。
當您創建一個新片段(通過調用 new SearchFragment()
,或者更好的是靜態方法SearchFragment.createInstance()
)時,您正在創建一個動態片段,可以通過FragmentTransaction
添加到擁有的Activity
的視圖(或其他Fragment
)布局。
有關Fragment
用法的更多詳細信息和示例代碼,請參閱 此頁面。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.