Snippet setuserVisibleHint true but getActivity returns null

I did some logic inside the fragment method setUserVisibleHint(). I always checked if isVisibleToUsertrue, and then used getActivityto return activity. This worked well (100% of the time) until I updated the support library to the latest ( support:appcompat-v7:24.2.0). Now getActivityalways returns null. Are there any changes to the support library that explain this behavior?

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

    if (isVisibleToUser) {
      getActivity() <- null
    }
+4
source share
4 answers

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;
                }
            }

    }
+2
source

Google: " Android N , , setUserVisibleHint , FragmentTransaction . , targetSdkVersion 23 ."

, :  1. targetSdkVersion < 24;  2. = > , , onAttach ;

+2

, , , -. , . , , setUserVisibleHint. , , , onAttach. . .

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
    }
}
+1
source
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser && (getActivity()!=null)) {
     getActivity();
    }
}

first time getActivity () is Nullable

0
source

Source: https://habr.com/ru/post/1654784/


All Articles