zoukankan      html  css  js  c++  java
  • Android: Fragment (Trying to instantiate a class that is not a Fragment)

    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"/>
    

      

  • 相关阅读:
    系统安装之:虚拟机VMware V12.0.1 专业版 + 永久密钥
    PHP之:析构函数
    HTML之:让网页中的<a>标签属性统一设置-如‘新窗口打开’
    HTML之:fieldset——一个不常用的HTML标签
    系统配置 之:远程桌面连接(win7系统)
    Code笔记 之:注册页面验证码
    PHP之:PHP框架
    Code笔记 之:防盗链(图片)
    Ehcache(2.9.x)
    Ehcache(2.9.x)
  • 原文地址:https://www.cnblogs.com/fuyoucaoyu/p/5650590.html
Copyright © 2011-2022 走看看