Android: Fragment (Trying to instantiate a class that is not a Fragment)
2024-09-10 08:29:38
Fragments API: https://developer.android.com/guide/components/fragments.html
第一次使用Fragment遇到一个问题就是:
Trying to instantiate a class xxx that is not a Fragment)
问题来由:
Fragment是Android3.0(API Level 11)才开始引入的,之前的API不能直接使用android.app.Fragment。
就出现了兼容低版本的放在android.support.v4.jar兼容包中的Fragment。
但是通过Activity的布局文件内声明Fragment时,<fragment>节点默认是使用android.app.Fragment中的Fragment。
如果想使用android.support.v4.app.Fragment,需要Activity继承android.support.v4.app.FragmentActivity。
解决方案:
1. 自定义的Fragment需要继承自android.app.Fragment而不是android.support.v4.app.Fragment
这个需要API最低版本也支持Fragment才行;
package com.example.helloservice.fragments; import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; import com.example.helloservice.R; /**
* create an instance of this fragment.
*/
public class ExampleFragment extends Fragment { @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
} @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_example, container, false);
} @Override
public void onAttach(Activity activity) {
super.onAttach(activity);
} @Override
public void onDetach() {
super.onDetach();
} }
2. Activity继承自FragmentActivity而不是Activity
public class ExampleFragment extends android.support.v4.app.Fragment {
....
} public class MainActivity extends android.support.v4.app.FragmentActivity {
....
} xml:
<fragment
android:name="com.example.helloservice.fragments.ExampleFragment"
android:id="@+id/exampleFragment"
android:tag="@string/hello_blank_fragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="300dp"/>
最新文章
- django表单
- android加固系列—5.加固前先学会破解,hook(钩子)jni层系统api
- linux下如何修改weblogic console登陆的用户名和密码
- javascript设计模式-桥接模式
- 简单翻译和补充:1. GNU ARM Eclipse
- tc 2014 college tour 250 500
- PL/Sql 中创建、调试、调用存储过程
- android:installLocation简析
- php目录分隔符DIRECTORY_SEPARATOR
- vmware设置centos虚拟机nat联网(转)
- windows7 64bit下mvn命令后提示‘cmd’不是内部或外部命令,也不是可执行程序或批处理文件
- SpringBoot初体验(续)
- haproxy快速安装
- google colab 使用指南
- xrandr: 命令行修改分辨率工具
- 约瑟夫环(Joseph)的高级版(面向事件及“伪链表””)
- 基础知识--:before伪元素和:after伪元素
- 网站/IIS/Web/WCF服务 访问共享目录 映射 的解决方案
- [SoapUI] DataSource, DataSourceLoop, DataSink
- 【Android XML】Android XML 转 Java Code 系列之 style(3)
热门文章
- Android开发系列之事件拦截机制
- 如何:使用 Visual Basic 编写基于 Unity3D 的计算器
- Hadoop权威指南:通过FileSystem API读取数据
- requests从api中获取数据并存放到mysql中
- 吉特仓储管系统(开源)--使用Grunt压缩JS文件
- 使用VS Code从零开始开发调试.NET Core 1.1
- 【Java】Objects 源码学习
- STM32单片机学习心得——概述
- C++ 头文件系列(ios)
- 64位win2003 IIS6运行32位的.NET程序