onAttach activity is null

In creation of a fragment, I encountered getActivity() to be null. So to narrow down the problem, I kept a local copy of activity in onAttach(Activity activity), which by definition is when it is attached to an activity.

However, I logged the activity in onAttach, and it is still null.

I'm only running into this problem in 2.3.6 and below.

Is this a known problem with support package?


The series of methods called to bring a fragment up to resumed state are:

  • onAttach(Activity) called once the fragment is associated with its activity.
  • onCreate(Bundle) called to do initial creation of the fragment.
  • onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment.
  • onActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity.onCreate().
  • onViewStateRestored(Bundle) tells the fragment that all of the saved state of its view hierarchy has been restored.
  • onStart() makes the fragment visible to the user (based on its containing activity being started).
  • onResume() makes the fragment interacting with the user (based on its containing activity being resumed).
  • The bold method should be the one where getActivity doesn't return null anymore.

    the onAttach method should not be used to call methods of the activity object, It should be used to initialise callback interfaces. An example of these interfaces can be found here.


    这个问题是因为支持包,它意味着片段是从android 3.0开始的,并且是API级别11和UP,因此您肯定会遇到android 2.3.6姜鸟应用崩溃

    this.getActivity();
    
    链接地址: http://www.djcxy.com/p/70182.html

    上一篇: 数独解决方法

    下一篇: onAttach活动为空