Android中抛出android.app.Fragment$InstantiationException异常
16lz
2021-01-26
在照着郭霖的《第一行代码》第二版写酷欧天气时,开头是在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。所以解决方法有两种:
- 将ChooseAreaFragment继承的Fragment改为android.app.Fragment即可;
- 要想在Activity中使用android.support.v4.app.Fragment,可以让MainActivity继承FragmentActivity。
按照上面两种方法来解决后,运行就不会报错了。
更多相关文章
- Android上实现一个简单的天气预报APP(二) 配置布局
- Android(安卓)学习之路3
- 简述Android六大布局
- Xamarin Android开发实战(上册)
- android ViewFilpper(一)
- Android二维码生成与扫描
- RecyclerView嵌套GridView,RecyclerView的第一个item显示不全
- Android(安卓)Studio 2.2 新功能详解
- Android:使用ViewFlipper实现上下滚动消息