3

我有一个FragmentPagerAdapter创建它的子页面(它们是ListFragments),如下所示:

@Override
public Fragment getItem(int position) {
    return FragmentChildPage.newInstance();
}

我给 ViewPager 一个OffscreenPageLimit1。孩子ListFragments有一个 custom ScrollListener

我遇到的问题是自定义滚动侦听器仅适用于ListFragments当 ViewPager 滑过其时创建的OffscreenPageLimit子页面,即子页面> 2。

更令人困惑的是,如果我滚动几页然后返回滚动侦听器现在可以工作的第一页。

这里发生了什么?似乎ViewPager干扰了一些子页面OnScrollListener

谢谢

4

1 回答 1

5

试试这个。为我工作!

public class ActivityTest extends SherlockFragmentActivity {

    private ViewPager mViewPager;

    private TestAdapter mAdapter;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);

        mViewPager = new ViewPager(this);
        mViewPager.setId(android.R.id.button1);
        setContentView(mViewPager);

        mAdapter = new TestAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(mAdapter);
    }

    private class TestAdapter extends FragmentPagerAdapter {

        public TestAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return TestListFragment.newInstance(position);
        }

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

    }

    private static class TestListFragment extends SherlockListFragment {

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

        private String[] mItems = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9","0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };

        private int mPos;

        @SuppressLint("ValidFragment")
        public static TestListFragment newInstance(int pos) {
            TestListFragment frag = new TestListFragment();
            Bundle b = new Bundle();
            b.putInt("pos", pos);
            frag.setArguments(b);
            return frag;
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            mPos = getArguments().getInt("pos");
        }

        @Override
        public void onViewCreated(View view, Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);

            setListAdapter(new ArrayAdapter<String>(getSherlockActivity(), android.R.layout.simple_list_item_1, mItems));

            getListView().setOnScrollListener(new OnScrollListener() {              
                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {

                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                    Log.d(TAG, "onScroll() - Fragment: " + mPos);
                }
            });
        }
    }

}
于 2013-03-07T10:23:08.123 回答