问题: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 何时在 ViewPager 中可见
How to determine when Fragment becomes visible in ViewPager
您可以通过在 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 {
}
}
}
这篇关于如何确定 Fragment 何时在 ViewPager 中可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!