android get activity returns null

前端 未结 2 1002
再見小時候
再見小時候 2020-11-28 11:20

I am using Action Bar on an Activity. For each Tab I am showing different layout. Since the layout is too heavy. So I am inflating each layout into a view. So on each Tab se

相关标签:
2条回答
  • 2020-11-28 12:09

    This can happen if you create an anonymous object inside a fragment that calls getActiviy(). If getActivity() is called in the anonymous object after the fragment is popped off the fragment stack, getActivity() will return null. At that point, the fragment is no longer associated with an activity.

    0 讨论(0)
  • 2020-11-28 12:14

    The problem is most likely that you're using an old Fragment that has been detached from your Activity.

    So, the first time you create your Fragment, it is attached to your activity. All is good. Then when you change tab, your fragment might or might not be detached from the activity. When you tab back to it, the old fragment may be detached from the activity and so getActivity() returns null.

    This can happen if you're trying to keep references to your Fragments, rather than accessing them via the FragmentManager.

    It can also happen if your adapter is returning a reference to a fragment rather than a new fragment. I've fallen into this trap.

    (Posting the code where you create your fragments might help)

    Edit

    Maybe have a look at this and how they create add their ActionBar listeners. You need scope to your Activity. The way they do it is to define the listener in the Activity/Fragment (via implementing an interface) and then attach it to the Tab. This will give you scope and is probably a more stable way of doing things.

    0 讨论(0)
提交回复
热议问题