在照着郭霖的《第一行代码》第二版写酷欧天气时,开头是在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. Android上实现一个简单的天气预报APP(二) 配置布局
  2. Android(安卓)学习之路3
  3. 简述Android六大布局
  4. Xamarin Android开发实战(上册)
  5. android ViewFilpper(一)
  6. Android二维码生成与扫描
  7. RecyclerView嵌套GridView,RecyclerView的第一个item显示不全
  8. Android(安卓)Studio 2.2 新功能详解
  9. Android:使用ViewFlipper实现上下滚动消息

随机推荐

  1. iOS 和 Android(安卓)哪个更利于赚钱?
  2. Android实战技巧之四十四:Hello,Native!
  3. 环球旅讯 Android使用报道
  4. Android的 学习资料分享
  5. android定时关机
  6. 10个经典的Android开源应用项目
  7. Android之Handler分享
  8. Android为每个应用程序分配的内存大小是
  9. Android系统服务-简介
  10. 13-5-16 Android自定义空间实现wifi信号