Cannot resolve method getActivity()

心不动则不痛 提交于 2019-12-18 04:31:19

问题


  • 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

回答1:


You can use:

this Or `MainActivity.this`

Instead of:

getActivity()



回答2:


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.




回答3:


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);
    }


来源:https://stackoverflow.com/questions/32527199/cannot-resolve-method-getactivity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!