search

Home  >  Q&A  >  body text

android - Fragment的Context问题

mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

在Fragment 下 LineraLayoutManger第一个参数是context 但是可以使用getActivity()
它返回的是FragmentActivity 为什么啊

getActivity();
getContext();
getView().getContext();
getActivity().getApplicationContext();

这四者 有什么区别啊 新手 不太懂

怪我咯怪我咯2772 days ago592

reply all(1)I'll reply

  • 黄舟

    黄舟2017-04-17 17:42:42

    To summarize,
    getActivity(): returns Activity;
    getContext(): returns Context;
    Both are methods of Fragment, but Activity does not. In most cases, there is no difference between the two. In the new version of the Support Library package, Fragment does not There is a difference when held by Activity

    Why can we use getActivity() even though the parameter is context?
    Because Activity indirectly inherits Context (you can check the source code yourself), but Context is not Activity
    Reference: What is the difference between this, getContext() and getActivity()?

    View.getContext(): Returns the Context of the currently running View, usually the currently activated Activity;
    Activity.getApplicationContext(): Returns the Context of the entire application, when the Context you need to use exceeds the life cycle of the current Activity When using
    Reference: Difference between getContext() , getApplicationContext() , getBaseContext() and “this”

    So, you must be good at Google and good at summarizing. . .

    reply
    0
  • Cancelreply