Fragment中用getActivity获取上下文对象时,可能为null

版权声明:保留记忆 https://blog.csdn.net/u012811342/article/details/80493352

问题分析:
在fragment向activity传值时需要使用onAttach方法,由于onAttach(activity,Activity):void已被弃用,只能用onAttach(contex,Contex):void,但是在API<23时并不会去调用此方法,即会导致程序崩溃(此为google一个bug)。

解决办法:

@SuppressWarnings("deprecation")
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.activity = (FragmentActivity) activity;
    }

注:直接在onAttach中把上下文对象取出来,尽量避免使用getActivity().在测试的时候,在5.0的手机上测试,发现无论是onAttach的两个方法都初始化了,并没有出现在API小于23的情况下onAttach(Context   context)没有调用的情况。最后经过查找资料,当继承的Frament为support.v4.app.Fragment时,两个方法都会调用。当Fragment为android.app.Fragment时,会出现上述问题。

猜你喜欢

转载自blog.csdn.net/u012811342/article/details/80493352