Android: Fragment (Trying to instantiate a class that is not a Fragment)

本文介绍了在Android开发中使用Fragment时遇到的兼容性问题及解决方案。由于Fragment是Android 3.0之后引入的新特性,为了解决低版本系统兼容问题,需要通过自定义Fragment继承自不同的基类或者让Activity继承自FragmentActivity。

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

  

 

转载于:https://www.cnblogs.com/fuyoucaoyu/p/5650590.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值