PullToRefresh是否与FragmentPagerAdapter一起使用?

时间:2013-01-23 00:05:12

标签: android viewpagerindicator pull-to-refresh

库:

示例PullToRefreshListInViewPagerActivity仅适用于PageAdapter。

我无法找到一种方法将其用于FragmentPageAdapter

示例:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ptr_list_in_vp);

        mViewPager = (ViewPager) findViewById(R.id.vp_list);
        mViewPager.setAdapter(new ListViewPagerAdapter());
    }

    private class ListViewPagerAdapter extends PagerAdapter {

        @Override
        public View instantiateItem(ViewGroup container, int position) {
            Context context = container.getContext();

            PullToRefreshListView plv = (PullToRefreshListView) LayoutInflater.from(context).inflate(
                    R.layout.layout_listview_in_viewpager, container, false);

            ListAdapter adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1,
                    Arrays.asList(STRINGS));
            plv.setAdapter(adapter);

            plv.setOnRefreshListener(PullToRefreshListInViewPagerActivity.this);

            // Now just add ListView to ViewPager and return it
            container.addView(plv, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

            return plv;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

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

    }

    @Override
    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
        new GetDataTask(refreshView).execute();
    }

    private static class GetDataTask extends AsyncTask<Void, Void, Void> {

        PullToRefreshBase<?> mRefreshedView;

        public GetDataTask(PullToRefreshBase<?> refreshedView) {
            mRefreshedView = refreshedView;
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Simulates a background job.
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            mRefreshedView.onRefreshComplete();
            super.onPostExecute(result);
        }
    }

}

1 个答案:

答案 0 :(得分:3)

您可以将ListFragment添加到FragmentPageAdapter(或FragmentStatePageAdapter)并在其上添加“Pull-To-Refresh”功能。

Android-PullToRefresh存储库有一个关于ListFragment

的示例

Android开发者网站提供了有关如何制作FragmentPagerAdapterFragmentStatePagerAdapter的示例代码。

您还可以查看我的测试项目:https://github.com/caiguanhao/FSPAtest