Using context in a fragment

后端 未结 30 3149
Happy的楠姐
Happy的楠姐 2020-11-22 00:05

How can I get the context in a fragment?

I need to use my database whose constructor takes in the context, but getApplicationContext() and Fragmen

30条回答
  •  深忆病人
    2020-11-22 00:29

    Use fragments from Support Library -

    android.support.v4.app.Fragment
    

    and then override

    void onAttach (Context context) {
      this.context = context;
    }
    

    This way you can be sure that context will always be a non-null value.

提交回复
热议问题