在使用Fragment的时候遇到很多坑,下面记录一下:
1.(慎用)在布局xml文件中使用fragment报错(android.view.InflateException: Binary XML file line #5: Binary XML file line #5: Error inflating class fragment)———-
关于这种报错,有多种可能。
Activity可以继承FragmentActivity也可以是AppCompatActivity
xml文件的书写
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="@+id/fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.example.administrator.fragmentdemo.OneFragment"
/>
</RelativeLayout>
2.推荐使用
下面方法add(),replace()报错,注意这里的Fragment继承的是v4包的Fragment**
下面方法二选一
getSupportFragmentManager().beginTransaction().add(R.id.fragmentContainer,oneFragment).commitAllowingStateLoss();
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer,oneFragment).commitAllowingStateLoss();
布局文件如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
3.尽量不要用app包中的fragment,因为这个是在3.0之后才有的,支持的版本太高,在低版本中是是用不了的