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
基础教程推荐
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01