Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

android - 如何确定片段何时在ViewPager中可见(How to determine when Fragment becomes visible in ViewPager)

Problem: Fragment onResume() in ViewPager is fired before the fragment becomes actually visible. (问题:在片段实际可见之前,已触发ViewPager片段onResume() 。)

For example, I have 2 fragments with ViewPager and FragmentPagerAdapter . (例如,我有2个带有ViewPagerFragmentPagerAdapter 。) 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). (第二个片段仅适用于授权用户,我需要让用户在该片段可见时登录(使用警报对话框)。)

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. (但是,当第一个片段可见时, ViewPager会创建第二个片段,以便缓存第二个片段,并在用户开始滑动时使其可见。)

So the onResume() event is fired in the second fragment long before it becomes visible. (因此, onResume()事件在它可见之前就在第二个片段中触发了。) 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. (这就是为什么我试图找到一个事件,该事件在第二个片段变得可见时触发,并在适当的时候显示一个对话框。)

How can this be done? (如何才能做到这一点?)

  ask by 4ntoine translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How to determine when Fragment becomes visible in ViewPager (如何确定片段何时在ViewPager中可见)

You can do the following by overriding setUserVisibleHint in your Fragment : (你可以通过覆盖以下setUserVisibleHint在你的Fragment :)

public class MyFragment extends Fragment {
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
        }
        else {
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...