FragmentStatePagerAdapter onPageSelected 事件

FragmentStatePagerAdapter onPageSelected event(FragmentStatePagerAdapter onPageSelected 事件)

本文介绍了FragmentStatePagerAdapter onPageSelected 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 FragmentStatePagerAdapter,里面有 6 个片段.

I have a FragmentStatePagerAdapter with 6 fragments inside.

每个 Fragment 都连接到服务器并加载数据.

Each Fragment connect's to the server and loads data.

现在,服务器连接正在 Fragment.onStart() 中完成,这意味着在任何时候,我都有 3 个 http 请求(选定的 Fragment,每边一个).

Right now, the server connection is being done in Fragment.onStart(), that means that at any moment, I have 3 http requests going (the selected Fragment, and one to each side).

我想要的是当时只有一个连接,所以我想使用

What I want is to have only one connection at the time, so I figure to use

 viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
 { 
    @Override
    public void onPageSelected(final int position)
    {
        CustomFragment fragment = (CustomFragment) myFragmentStatePagerAdapter.getItem(position);

        fragment.onSelected();//do stuff in here
    }
 });

问题是,getItem() 返回片段的新实例,尚未添加到管理器(因此,尚未创建视图等).

The thing is, getItem() returns a new instance of the fragment, not yet added to the manager (and thus, not yet view created, etc).

另外,我试过 setUserVisibleHint(boolean isVisibleToUser) 但没有被调用可见,仅在 isVisibleToUser = false

Also, I've tried setUserVisibleHint(boolean isVisibleToUser) but is not being call on visible, only on isVisibleToUser = false

那么,如何为Fragment实现onPageSelected()"事件呢?

So, how to achieve a "onPageSelected()" event for the Fragment?

提前致谢

推荐答案

对你来说最好的解决方案是重写 setUserVisibleHint().确保你扩展了 FragmentPagerAdapter.从它的源代码可以看到也为可见片段调用 setUserVisibleHint(true).我一直在使用它,而且效果很好.

The best solution for you would be to override setUserVisibleHint(). Make sure you extend FragmentPagerAdapter. From its source code you can see it calls setUserVisibleHint(true) for visible fragments too. I use it all the time and it works well.

// adapter
public static class PlayerAdapter extends FragmentStatePagerAdapter {
    public PlayerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public int getCount() {
        return 6;
    }

    @Override
    public Fragment getItem(int position) {
        return new SimpleFragment();
    }
}

// fragment
public class SimpleFragment extends Fragment {

    private static final String TAG = BookControlsFragment.class.getSimpleName();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_simple, container, false);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.d(TAG, "setUserVisibleHint: " + isVisibleToUser);
    }
}

这篇关于FragmentStatePagerAdapter onPageSelected 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:FragmentStatePagerAdapter onPageSelected 事件

基础教程推荐