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

来源:互联网 发布:手动榨汁机好用么 知乎 编辑:程序博客网 时间:2024/05/22 07:01

在照着郭霖的《第一行代码》第二版写酷欧天气时,开头是在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。

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

0 0
原创粉丝点击