加载第一个 Fragment 后 ViewPager 调用 setUserVisibleHint

ViewPager call setUserVisibleHint after first Fragment is loaded(加载第一个 Fragment 后 ViewPager 调用 setUserVisibleHint)
本文介绍了加载第一个 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to target newer versions in .gitlab-ci.yml using auto devops (java 11 instead of 8 and Android 31 instead of 29)(如何在.gitlab-ci.yml中使用自动开发工具(Java 11而不是8,Android 31而不是29)瞄准较新的版本)
Android + coreLibraryDesugaring: which Java 11 APIs can I expect to work?(Android+core LibraryDesugering:我可以期待哪些Java 11API能够工作?)
How to render something in an if statement React Native(如何在If语句中呈现某些内容Reaction Native)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)
Using Firebase Firestore in offline only mode(在仅脱机模式下使用Firebase FiRestore)
Crash on Google Play Pre-Launch Report: java.lang.NoSuchMethodError(Google Play发布前崩溃报告:java.lang.NoSuchMethodError)