Why is my context in my Fragment null?

前端 未结 4 1339
耶瑟儿~
耶瑟儿~ 2020-12-07 01:04

I have got a question regarding the usage of context in a fragment. My problem is that I always get a NullpointerException. Here is what i do:

Create a class that ex

4条回答
  •  死守一世寂寞
    2020-12-07 02:07

    Hi the question has answered, but generally if you want to get context in fragment or dialogFragment use this

    protected lateinit var baseActivity: BaseActivity
    protected lateinit var contextFragment: Context
    
    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is BaseActivity) {
            this.baseActivity = context
        }
        this.contextFragment = context
    }
    

    and in java

     protected BaseActivity baseActivity;
     protected Context context;
    
     @Override
     public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.context = context;
        if (context instanceof BaseActivity) {
            this.baseActivity = (BaseActivity) context;
        }
    }
    

提交回复
热议问题