Cannot resolve method getActivity()

2019-02-11 19:44发布

  • I am new to Android and learning to create fragments in Android by following this
    example: Fragment Navigation Drawer

  • The code between Navigating between Menu Items and Add Navigation Header consists a method getActivity().

  • As the author didn't mentioned where to paste this code, I pasted in my MainActivity.java file

  • Is code between Navigating between Menu Items and Add Navigation Header pasted at correct location by me?

  • In method selectDrawerItem(MenuItem menuItem) there is a comment // Create a new fragment and specify the planet to show based on position
    Does author expects me to add something over here.

  • The project files layout created by me on AndroidStudio is as follow:AndroidStudio Snapshot

3条回答
祖国的老花朵
2楼-- · 2019-02-11 20:25

An Activity has no getActivity() method.
Fragments have.

Because getActivity() says: "return the Activity which contains me".

And while Framents are contained in Activities, Activities themselves aren't.

查看更多
Melony?
3楼-- · 2019-02-11 20:30

You can use:

this Or `MainActivity.this`

Instead of:

getActivity()
查看更多
Melony?
4楼-- · 2019-02-11 20:41

In Fragment it is best to use onAttach() method to get the instance of an Activity attached to it.

@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }
查看更多
登录 后发表回答