Android中抛出android.app.Fragment$InstantiationException异常

在照着郭霖的《第一行代码》第二版写酷欧天气时,开头是在MainActivity中填充ChooseAreaFragment。书里的写法是在MainActivity的布局文件activity_main.xml中将Fragment作为一个控件放置进去:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <fragment
        android:id="@+id/choose_area_fragment"
        android:name="com.lindroid.coolweather.ChooseAreaFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</FrameLayout>

代码看起来没有问题,但是运行之后却崩溃了,抛出了下面这个异常:

Caused by: android.app.Fragment$InstantiationException: Trying to instantiate a class com.lindroid.coolweather.ChooseAreaFragment that is not a Fragment

这是因为在布局文件中使用的fragment节点设置Fragment时,默认的是android.app.Fragment,而我在创建ChooseAreaFragment时继承的是android.support.v4.app.Fragment。所以解决方法有两种:

  1. 将ChooseAreaFragment继承的Fragment改为android.app.Fragment即可;
  2. 要想在Activity中使用android.support.v4.app.Fragment,可以让MainActivity继承FragmentActivity。

按照上面两种方法来解决后,运行就不会报错了。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值