Android setUserVisibleHint never gets called?
Asked Answered
M

2

18

I need to know when my fragment is visible, I was using setMenuVisibility but I now know it's not a good option. I'm trying to implement setUserVisibleHint on a FragmentStatePagerAdapter Fragment, however it never gets called.

import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;


public class Contacts extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            View view = inflater.inflate(R.layout.fragment_screen_contacts, container, false);
            return view;
        }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.d("MyFragment", "This never shows up.");
        Toast.makeText(getActivity(), "Neither does this", Toast.LENGTH_LONG).show();
    }
}

I'm running API level 19, and set a minimum API Level of 15 on my AndroidManifest. Is there anything else to do to get setUserVisibleHint, what am I doing wrong?

Mindful answered 8/3, 2014 at 13:17 Comment(4)
Try to call before check condition super.setUserVisibleHint(isVisibleToUser);Innumerable
I just tried and it's the same. I read this only works after api level 15. I'm trying to check my API level to se if it's thatMindful
I changed android:minSdkVersion to 16 but it still doesn't work. It seems the problem is not with the class or somebody would have seen itMindful
Hi. Which support library are you using, which revision?Gillispie
C
19

setUserVisibleHint is available so that you have a way to tell the system the fragment is in fact not visible and not the other way around, when you are doing some fancy fragment transactions that specifically hide it. You can't use it to determine visibility and it defaults to true.

You should use the isVisible call to know if the fragment is visible and onAttach of the fragment or the root view classes to get callbacks when it's been attached to the activity or the respective root views.

Consummate answered 12/3, 2014 at 5:56 Comment(0)
B
19
setUserVisibleHint() 

only works in a FragmentPagerAdapter. Please refer to Is Fragment.setUserVisibleHint() called by the android System?

Barbabra answered 2/3, 2016 at 2:46 Comment(1)
android.support.v13.app.FragmentPagerAdapter works for me.Kutz

© 2022 - 2024 — McMap. All rights reserved.