关于Fragment的使用

在使用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之后才有的,支持的版本太高,在低版本中是是用不了的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值