ViewPager call setUserVisibleHint after first Fragment is loaded(加载第一个 Fragment 后 ViewPager 调用 setUserVisibleHint)
问题描述
在我的应用程序中,我有一个 ViewPager,其中包含许多带有 Fragment 的可滑动标签.我使用 setUserVisibleHint
方法来检测 Fragment
何时出现在屏幕上.当用户在选项卡之间滑动但在第一次加载时不起作用时,这非常有用.要运行该方法中的代码,我必须向左滑动,然后返回到第一个 Fragment
,因为在 onCreateView
之前调用了 setUserVisibleHint
方法方法.
In my application, I have a ViewPager which holds many swipeable Tabs with Fragments inside. I use the setUserVisibleHint
method to detect when a Fragment
comes to the screen. This works great when the user swipes between tabs but it does not work on the first load. To run the code in the method I have to swipe to left and then back to the first Fragment
because the setUserVisibleHint
method is called before the onCreateView
method.
您知道如何在第一个 Fragment 可见后运行此代码吗?ViewPager
中是否有方法或其他内容?
Do you have any ideas how I can run this code after the first Fragment is visible? Is there a method in the ViewPager
or something else?
推荐答案
您不能(也不应该)为此依赖 setUserVisibleHint
.相反,您应该使用 ViewPager.OnPageChangeListener 来获取回调当页面变得可见时.例如
You can't (and shouldn't) rely on setUserVisibleHint
for this. Instead, you should be using a ViewPager.OnPageChangeListener to get callbacks for when a page becomes visible. E.g.
viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
// do your work
}
});
注意:如果不需要监听所有回调,可以使用ViewPager.SimpleOnPageChangeListener
.
Note: You can use ViewPager.SimpleOnPageChangeListener
if you don't need to listen for all callbacks.
setOnPageChangeListener
方法现已弃用,请改用 addOnPageChangeListener
setOnPageChangeListener
method is now deprecated, use addOnPageChangeListener
instead
viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
// do your work
}
});
这篇关于加载第一个 Fragment 后 ViewPager 调用 setUserVisibleHint的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:加载第一个 Fragment 后 ViewPager 调用 setUserVisibleHint
- 如何在 iPhone 模拟器中重置 NSUserDefaults 数据? 2022-01-01
- Xcode 7.3 中带有 UILabel 的 UIStackView 2022-01-01
- GPS状态的广播接收器? 2022-01-01
- URL编码Swift iOS 2022-01-01
- 网上有没有好的 UIScrollView 教程? 2022-01-01
- UITextView 内容插图 2022-01-01
- SetOnItemSelectedListener上的微调程序错误 2022-01-01
- 使用自动布局向 UIScrollView 添加动态大小的视图 2022-01-01
- 在 Iphone SDK 的导航栏上添加多个按钮 2022-01-01
- 类似于 Mail.app 的 iPad 模态视图控制器? 2022-01-01