Fragment setuserVisibleHint true but getActivity returns null

痴心易碎 提交于 2019-12-05 06:31:35

I'm a bit late to the party but maybe this can help someone. I solved this problem by creating a boolean member inside the fragment class. I used this then to determine whether or not I was able to successfully get the activity in the setUserVisibleHint method. If not, I execute the activity-related code in onAttach. See below.

public MyFragment extends Fragment {

    ...

    private boolean doInOnAttach = false;

    @Override
    public void setUserVisibleHint(boolean visible) {
        super.setUserVisibleHint(visible);
        // if the fragment is visible
        if (true == visible) {
            // ... but the activity has not yet been initialized
            doInOnAttach = true;
        } else {
            myAction();
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (true == doInOnAttach) {
            myAction();
            doInOnAttach = false;
        }
    }

    private void myAction() {
        // code to execute here
    }
}

Below Worked for me....

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState)
{
    //// create class member variable to store view
    viewFrag =inflater.inflate(R.layout.fragment_main_favorite, container, false);

    // Inflate the layout for this fragment
    return viewFrag;
}

and use this

@Override
    public void setUserVisibleHint(boolean visible)
    {
        super.setUserVisibleHint(visible);


            if (visible)
            {

                View v =  viewFrag ;
                if (v == null) {
                    Toast.makeText(getActivity(), "ERROR ", Toast.LENGTH_LONG ).show();
                    return;
                }
            }

    }

According to Google: "Prior to Android N there was a platform bug that could cause setUserVisibleHint to bring a fragment up to the started state before its FragmentTransaction had been committed. As some apps relied on this behavior, it is preserved for apps that declare a targetSdkVersion of 23 or lower."

So, there are two options: 1. rebuild with targetSdkVersion < 24; 2. modify the app according to new situation => use the context outside this callback, respectively in onAttach method or later on in the fragment lifecycle;

public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser && (getActivity()!=null)) {
     getActivity();
    }
}

at first lunch getActivity() is Nullable

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