Android setUserVisibleHint never gets called?

好久不见. 提交于 2019-11-29 11:39:57

问题


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?


回答1:


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.




回答2:


setUserVisibleHint() 

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



来源:https://stackoverflow.com/questions/22269836/android-setuservisiblehint-never-gets-called

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