加载第一个 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:加载第一个 Fragment 后 ViewPager 调用 setUserVisibleHint

基础教程推荐