问题描述
问题:ViewPager
中的片段 onResume()
在片段实际可见之前被触发.
Problem: Fragment onResume()
in ViewPager
is fired before the fragment becomes actually visible.
例如,我有 2 个带有 ViewPager
和 FragmentPagerAdapter
的片段.第二个片段仅对授权用户可用,我需要在片段可见时要求用户登录(使用警报对话框).
For example, I have 2 fragments with ViewPager
and FragmentPagerAdapter
. The second fragment is only available for authorized users and I need to ask the user to log in when the fragment becomes visible (using an alert dialog).
但是 ViewPager
在第一个片段可见时创建第二个片段,以便缓存第二个片段并在用户开始滑动时使其可见.
BUT the ViewPager
creates the second fragment when the first is visible in order to cache the second fragment and makes it visible when the user starts swiping.
因此 onResume()
事件在第二个片段变得可见之前很久就会被触发.这就是为什么我试图找到一个事件,当第二个片段变得可见以在适当的时候显示一个对话框时触发.
So the onResume()
event is fired in the second fragment long before it becomes visible. That's why I'm trying to find an event which fires when the second fragment becomes visible to show a dialog at the appropriate moment.
如何做到这一点?
推荐答案
您可以通过覆盖 Fragment
中的 setUserVisibleHint
来执行以下操作:
You can do the following by overriding setUserVisibleHint
in your Fragment
:
public class MyFragment extends Fragment {
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
}
else {
}
}
}
这篇关于如何确定片段何时在 ViewPager 中可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!