将光标位置从listview传递到viewpager

时间:2014-03-03 21:34:57

标签: android position cursor android-viewpager android-cursoradapter

我在一个关于处理Feed的小项目中工作,我希望在listview中处理feed并在viewpager中显示详细信息,当我点击listview时我得到了相同的feed我失去了关于如何将光标位置传递给viewpaver < / p>

它是complet listfragment

public class EntryListFragmentt extends ListFragment
        implements  OnItemClickListener ,LoaderManager.LoaderCallbacks<Cursor>{

    private static final String TAG = "EntryListFragmentt";


    private OnItemSelectedListener mParentOnItemSelectedListener;

    /**
     * Cursor adapter for controlling ListView results.
     */
    private SimpleCursorAdapter mAdapter;

    public static ImageLoader imageLoader; 

    Uri detailUri;

    static int pos;

    private LoaderManager.LoaderCallbacks<Cursor> mCallbacks;

    /**
     * Handle to a SyncObserver. The ProgressBar element is visible until the SyncObserver reports
     * that the sync is complete.
     *
     * <p>This allows us to delete our SyncObserver once the application is no longer in the
     * foreground.
     */
    ConnectionDetector cd;

    private Object mSyncObserverHandle;

    /**
     * Options menu used to populate ActionBar.
     */
    private Menu mOptionsMenu;

    /**
     * Projection for querying the content provider.
     */
    private static final String[] PROJECTION = new String[]{
            FeedContract.Entry._ID,
            FeedContract.Entry.COLUMN_NAME_TITLE,
            FeedContract.Entry.COLUMN_NAME_LINK,

            FeedContract.Entry.COLUMN_IMAG_LINK,
            FeedContract.Entry.COLUMN_TEXT_ENTRY,
            FeedContract.Entry.COLUMN_NAME_PUBLISHED
    };

    // Column indexes. The index of a column in the Cursor is the same as its relative position in
    // the projection.
    /** Column index for _ID */
    private static final int COLUMN_ID = 0;
    /** Column index for title */
    private static final int COLUMN_TITLE = 1;
    /** Column index for link */
    private static final int COLUMN_URL_STRING = 2;
    /** Column index for published */


    private static final int COLUMN_IMAG_LINK = 3;

    private static final int COLUMN_TEXT_ENTRY = 4;
    private static final int COLUMN_PUBLISHED = 5;



    AlertDialogManager alert = new AlertDialogManager();

    /**
     * List of Cursor columns to read from when preparing an adapter to populate the ListView.
     */
    private static final String[] FROM_COLUMNS = new String[]{
            FeedContract.Entry.COLUMN_NAME_TITLE,
            FeedContract.Entry.COLUMN_NAME_PUBLISHED,
            FeedContract.Entry.COLUMN_NAME_LINK
           // FeedContract.Entry.COLUMN_TEXT_ENTRY
    };

    /**
     * List of Views which will be populated by Cursor data.
     */
    private static final int[] TO_FIELDS = new int[]{
            R.id.tx_title_actu,
            R.id.tx_date_actu,
            R.id.img_actu
           // R.id.tx_text_actu
            };

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */


    public static EntryListFragmentt newInstance() {
        return new EntryListFragmentt();
    }

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

    /**
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        //View view = inflater
        //      .inflate(R.layout.activity_entry_list, container, false);


                return container;

    }

    **/


    /**
     * Create SyncAccount at launch, if needed.
     *
     * <p>This will create a new account with the system for our application, register our
     * {@link SyncService} with it, and establish a sync schedule.
     */
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);



        // Create account, if needed
        SyncUtils.CreateSyncAccount(activity);
    }


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


        mAdapter = new SimpleCursorAdapter(
                getActivity(),       // Current context
                R.layout.actu_listitem,  // Layout for individual rows
                null,                // Cursor
                FROM_COLUMNS,        // Cursor columns to use
                TO_FIELDS,           // Layout fields to use
                0                    // No flags
        );
        mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {

            private String slink;

            @Override
            public boolean setViewValue(View view, Cursor cursor, int i) {


                if (i == COLUMN_PUBLISHED ) {
                    // Convert timestamp to human-readable date
                    Time t = new Time();
                    t.set(cursor.getLong(i));
                    ((TextView) view).setText(t.format("%Y-%m-%d %H:%M"));



                   // Drawable fimag = ResourceUtils.getDrawableByName( imaglink, getActivity());

                     //String faceName = "ic_launcher";


                    return true;
                } else if (i == COLUMN_URL_STRING ){

                 slink = CursorUtils.getString(FeedContract.Entry.COLUMN_NAME_LINK, cursor).trim();

                    // int vlink = Integer.parseInt(CursorUtils.getString(FeedContract.Entry.COLUMN_NAME_LINK, cursor));


                     ImageView vimage =(ImageView) view.findViewById(R.id.img_actu);


                    //vimage.setImageResource(getActivity().getResources().getIdentifier("app.oc.gov.ma:drawable/"+slink,null,null));


                     vimage.setImageDrawable(ResourceUtils.getDrawableByName(slink, getActivity()));

                    // imageLoader=new ImageLoader(getActivity().getApplicationContext());

                     //imageLoader.DisplayImage(imaglink, vimage);
                   // vimage.setImageResource(R.drawable.a);

                    // Let SimpleCursorAdapter handle other fields automatically
                     return true;

                } else  {

                    return false;
                }
            }
        });



        mCallbacks = this;
        setListAdapter(mAdapter);
        setEmptyText(getText(R.string.loading));
        getLoaderManager().initLoader(0, null, mCallbacks);

    }


    @Override
    public void onResume() {
        super.onResume();
        mSyncStatusObserver.onStatusChanged(0);

        // Watch for sync state changes
        final int mask = ContentResolver.SYNC_OBSERVER_TYPE_PENDING |
                ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE;
        mSyncObserverHandle = ContentResolver.addStatusChangeListener(mask, mSyncStatusObserver);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mSyncObserverHandle != null) {
            ContentResolver.removeStatusChangeListener(mSyncObserverHandle);
            mSyncObserverHandle = null;
        }
    }

    /**
     * Query the content provider for data.
     *
     * <p>Loaders do queries in a background thread. They also provide a ContentObserver that is
     * triggered when data in the content provider changes. When the sync adapter updates the
     * content provider, the ContentObserver responds by resetting the loader and then reloading
     * it.
     */
    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        // We only have one loader, so we can ignore the value of i.
        // (It'll be '0', as set in onCreate().)
        return new CursorLoader(getActivity(),  // Context
                FeedContract.Entry.CONTENT_URI, // URI
                PROJECTION,                // Projection
                null,                           // Selection
                null,                           // Selection args
             //   null); // Sort
        FeedContract.Entry.COLUMN_NAME_PUBLISHED + " desc"); // Sort
    }

    /**
     * Move the Cursor returned by the query into the ListView adapter. This refreshes the existing
     * UI with the data in the Cursor.
     */
    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        mAdapter.changeCursor(cursor);
    }

    /**
     * Called when the ContentObserver defined for the content provider detects that data has
     * changed. The ContentObserver resets the loader, and then re-runs the loader. In the adapter,
     * set the Cursor value to null. This removes the reference to the Cursor, allowing it to be
     * garbage-collected.
     */
    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
        mAdapter.changeCursor(null);
    }

    /**
     * Create the ActionBar.
     */
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        mOptionsMenu = menu;
        inflater.inflate(R.menu.main_actu, menu);
    }

    /**
     * Respond to user gestures on the ActionBar.
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {


            // If the user clicks the "Refresh" button.
            case R.id.menu_refresh:


                 cd = new ConnectionDetector(getActivity().getApplicationContext());

                 // Check for internet connection
                 if (!cd.isConnectingToInternet()) {
                     // Internet Connection is not present
                   setEmptyText(getText(R.string.noconnect));
                   alert.showAlertDialog(getActivity(), "Internet Connection Error",
                             "Please connect to working Internet connection", false);

                 }else {
                SyncUtils.TriggerRefresh();
                return true;
                 }
                 return false;  
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * Load an article in the default browser when selected by the user.
     */

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub

    }


    @Override
    public void onListItemClick(ListView listView, View view, int position, long id) {


        super.onListItemClick(listView, view, position, id);

        // Get a URI for the selected item, then start an Activity that displays the URI. Any
        // Activity that filters for ACTION_VIEW and a URI can accept this. In most cases, this will
        // be a browser.

        // Get the item at the selected position, in the form of a Cursor.
       Cursor c = (Cursor) mAdapter.getItem(position);
        // Get the link to the article represented by the item.

       Uri detailUri = Uri.parse(FeedContract.Entry.CONTENT_URI + "/" + id);


        WhatsOnFragment.newInstance(position,  detailUri);


        WhatsOnFragment WWhatsOnFragment = new WhatsOnFragment();

        FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction ft = fragmentManager.beginTransaction();

            ft.replace(R.id.frame_container, WWhatsOnFragment);

            //ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            //ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

            ft.addToBackStack(null);
            ft.commit();

    }

    public int getCount(int cmp) {

        return  cmp ;
    }


    public static WhatsOnFragment newInstance(int position,int cmp, Uri detailUri) {
        WhatsOnFragment frag = new WhatsOnFragment();

        Bundle args = new Bundle();
        args.putParcelable(FeedContract.Entry.CONTENT_ITEM_TYPE, detailUri);
        args.putInt(WhatsOnFragment.POSITION_KEY, position);
        frag.setArguments(args);
        return frag;
    }



    /**
     * Set the state of the Refresh button. If a sync is active, turn on the ProgressBar widget.
     * Otherwise, turn it off.
     *
     * @param refreshing True if an active sync is occuring, false otherwise
     */
    public void setRefreshActionButtonState(boolean refreshing) {
        if (mOptionsMenu == null) {
            return;
        }

        final MenuItem refreshItem = mOptionsMenu.findItem(R.id.menu_refresh);
        if (refreshItem != null) {
            if (refreshing) {
                refreshItem.setActionView(R.layout.actionbar_indeterminate_progress);
            } else {
                refreshItem.setActionView(null);
            }
        }
    }

    /**
     * Crfate a new anonymous SyncStatusObserver. It's attached to the app's ContentResolver in
     * onResume(), and removed in onPause(). If status changes, it sets the state of the Refresh
     * button. If a sync is active or pending, the Refresh button is replaced by an indeterminate
     * ProgressBar; otherwise, the button itself is displayed.
     */
    private SyncStatusObserver mSyncStatusObserver = new SyncStatusObserver() {
        /** Callback invoked with the sync adapter status changes. */
        @Override
        public void onStatusChanged(int which) {
            getActivity().runOnUiThread(new Runnable() {
                /**
                 * The SyncAdapter runs on a background thread. To update the UI, onStatusChanged()
                 * runs on the UI thread.
                 */
                @Override
                public void run() {
                    // Create a handle to the account that was created by
                    // SyncService.CreateSyncAccount(). This will be used to query the system to
                    // see how the sync status has changed.
                    Account account = GenericAccountService.GetAccount();
                    if (account == null) {
                        // GetAccount() returned an invalid value. This shouldn't happen, but
                        // we'll set the status to "not refreshing".
                        setRefreshActionButtonState(false);
                        return;
                    }

                    // Test the ContentResolver to see if the sync adapter is active or pending.
                    // Set the state of the refresh button accordingly.
                    boolean syncActive = ContentResolver.isSyncActive(
                            account, FeedContract.CONTENT_AUTHORITY);
                    boolean syncPending = ContentResolver.isSyncPending(
                            account, FeedContract.CONTENT_AUTHORITY);
                    setRefreshActionButtonState(syncActive || syncPending);
                }
            });
        }
    };


    }

它是片段详细信息viewpager

 public class WhatsOnFragment extends Fragment implements
            LoaderCallbacks<Cursor> {

        private static final String TAG="WhatsOnFragment";

        private OnItemSelectedListener mParentOnImageSelectedListener;



        private Handler mHandler = new Handler();

        private TextView mCountdownTextView;
        private ViewGroup mRootView;
        private Cursor mAnnouncementsCursor;
        private LayoutInflater mInflater;
        private int mTitleCol = -1;
        private int mDateCol = -1;
        private int mUrlCol = -1;

        //**********************************************''

        /** Column index for _ID */
        private static final int COLUMN_ID = 0;
        /** Column index for title */
        private static final int COLUMN_TITLE = 1;
        /** Column index for link */
        private static final int COLUMN_URL_STRING = 2;
        /** Column index for published */


        private static final int COLUMN_IMAG_LINK = 3;

        private static final int COLUMN_TEXT_ENTRY = 4;
        private static final int COLUMN_PUBLISHED = 5;

         private static final String[] PROJECTION = new String[]{
             FeedContract.Entry._ID,
             FeedContract.Entry.COLUMN_NAME_TITLE,
             FeedContract.Entry.COLUMN_NAME_LINK,

             FeedContract.Entry.COLUMN_IMAG_LINK,
             FeedContract.Entry.COLUMN_TEXT_ENTRY,
             FeedContract.Entry.COLUMN_NAME_PUBLISHED
     };

         public static String POSITION_KEY = "position"; 
         private static final int ANNOUNCEMENTS_LOADER_ID = 0;
         private Uri detailUri;

        public static int vpos;

        public static  WhatsOnFragment newInstance(int position, Uri detailUri) {
            WhatsOnFragment frag = new WhatsOnFragment();
            Bundle args = new Bundle();
            args.putInt(POSITION_KEY, position);
            //args.putParcelable(FeedContract.Entry.CONTENT_ITEM_TYPE, detailUri);
            frag.setArguments(args);
            return frag;
        }



        @Override
        public void onAttach(Activity activity) {
         super.onAttach(activity);
         Log.v(TAG, "onAttach");

        }

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

            //Bundle extras = getArguments();
            //vpos = extras.getInt(POSITION_KEY,0);
            //vpos = savedInstanceState.getInt(POSITION_KEY, 0);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            mInflater = inflater;

         // 


           mRootView = (ViewGroup) inflater.inflate(R.layout.content_f,
                   container,false);


            refresh();


            return mRootView;
        }


        @Override
        public void onDetach() {
            super.onDetach();
          // mHandler.removeCallbacks(mCountdownRunnable);
            getActivity().getContentResolver().unregisterContentObserver(mObserver);
        }

        private void refresh() {
           mHandler.removeCallbacks(mCountdownRunnable);
            //mRootView.removeAllViews();



                setupDuring();
                //getLoaderManager().initLoader(0, null, this);
        }

        private void setupDuring() {
            // Start background query to load announcements
            getLoaderManager().initLoader(0, null, this);
            getActivity().getContentResolver().registerContentObserver(
                    FeedContract.Entry.CONTENT_URI, true, mObserver);
        }

        /**
         * Event that updates countdown timer. Posts itself again to
         * {@link #mHandler} to continue updating time.
         */


        private final Runnable mCountdownRunnable = new Runnable() {
            public void run() {






                     mHandler.postDelayed(new Runnable() {
                         public void run() {


                             refresh();
                         }
                     }, 100);
                     return;

            }


        };



        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
             return new CursorLoader(getActivity(),  // Context
                     FeedContract.Entry.CONTENT_URI, // URI
                     PROJECTION,                // Projection
                     null,                           // Selection
                     null,                           // Selection args
                    // null);

                     FeedContract.Entry.COLUMN_NAME_PUBLISHED + " desc"); // Sort
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
            if (getActivity() == null) {
                return;
            }
            if (data != null && data.getCount() > 0) {
                mTitleCol = data.getColumnIndex(FeedContract.Entry.COLUMN_NAME_TITLE);
                mDateCol = data.getColumnIndex(FeedContract.Entry.COLUMN_TEXT_ENTRY);


                showAnnouncements(data);

            }
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {
            mAnnouncementsCursor = null;
        }

        /**
         * Show the the announcements
         */
        private void showAnnouncements(Cursor announcements) {
            mAnnouncementsCursor = announcements;






            ViewGroup announcementsRootView = (ViewGroup) mInflater.inflate(
                    R.layout.detail, mRootView, false);

            final ViewPager pager = (ViewPager) announcementsRootView.findViewById(
                    R.id.pager);


            final PagerAdapter adapter = new AnnouncementsAdapter();
            pager.setAdapter(adapter);
            //pager.setCurrentItem(0);

            pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {

                    pager.setCurrentItem(pager.getCurrentItem());


                }

                @Override
                public void onPageScrollStateChanged(int state) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                    // TODO Auto-generated method stub
                    //Toast.makeText(getActivity().getApplicationContext(),"myposition  " + position,Toast.LENGTH_LONG).show();

                }
            });


            //mRootView.removeAllViews();
            mRootView.addView(announcementsRootView);
        }



        public class AnnouncementsAdapter extends PagerAdapter {

            @Override
            public Object instantiateItem(ViewGroup pager, int position) {



              mAnnouncementsCursor.moveToPosition(position);

                View rootView = (View) mInflater.inflate(
                        R.layout.detail_fragment, pager, false);
                TextView titleView = (TextView) rootView.findViewById(R.id.title);
                TextView subtitleView = (TextView) rootView.findViewById(R.id.description);


                //WebView desc = (WebView) rootView.findViewById(R.id.desc);

                // Enable the vertical fading edge (by default it is disabled)
                ScrollView sv = (ScrollView) rootView.findViewById(R.id.sv);
                sv.setVerticalFadingEdgeEnabled(true);

                // Set webview properties
                //WebSettings ws = desc.getSettings();
                //ws.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
                //ws.setLightTouchEnabled(false);
                //ws.setPluginState(PluginState.ON);
                //ws.setJavaScriptEnabled(true);


                titleView.setText(mAnnouncementsCursor.getString(mTitleCol));
                subtitleView.setText(mAnnouncementsCursor.getString(mDateCol));

                //desc.loadDataWithBaseURL("http://.../",mAnnouncementsCursor.getString(mDateCol), "text/html", "UTF-8", null);


                pager.addView(rootView, 0);
                return rootView;
            }



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

            @Override
            public int getCount() {
                return mAnnouncementsCursor.getCount();
            }

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

            @Override
            public int getItemPosition(Object object) {
                return POSITION_NONE;
            }

            public Object getItem(int position) {

                WhatsOnFragment frag = new WhatsOnFragment();
                Bundle args = new Bundle();
                args.putInt(POSITION_KEY, position);
                //args.putParcelable(FeedContract.Entry.CONTENT_ITEM_TYPE, detailUri);
                frag.setArguments(args);

                if (position > 0 && position < mAnnouncementsCursor.getCount() - 1) {
                    return position;
                }
                return position;

            }
        }

        private final ContentObserver mObserver = new ContentObserver(new Handler()) {
            @Override
            public void onChange(boolean selfChange) {
                if (getActivity() == null) {
                    return;
                }

                Loader<Cursor> loader = getLoaderManager().getLoader(ANNOUNCEMENTS_LOADER_ID);
                if (loader != null) {
                    loader.forceLoad();
                }
            }
        };

    }

2 个答案:

答案 0 :(得分:0)

以下是我将Uri从一项活动传递到另一项活动的方式:

从onListItemClick获取uri后,在此之后添加以下代码:

String uriString = uri.toString();

现在,您可以通过共享首选项或通过传递来自intent的额外内容来实现,

方法1:按共享偏好设置:

SharedPreferences prefs = getSharedPreferences("your_file_name", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("uri", uriString);
editor.commit();

然后,在您的其他活动或定义列表视图的位置,使用此选项来检索uri,

SharedPreferences mPreferences = mPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String uri = mPreferences.getString("uri", uri);
//To parse the uri
Uri newUri = Uri.parse(uri);

然后您可以使用此uri获取您想要的信息。

方法2:从意图中获取uri:

首先:在你获得Uri的活动中,

Intent myIntent = new Intent(SomeActivity1.this, SomeActivity2.class);  


            myIntent.putExtra("uri", uri);
            myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            myIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            setResult(RESULT_OK, myIntent);
            startActivity(myIntent);

在您的其他活动或定义了列表视图的位置,使用此方法检索uri,

Intent data = getIntent();
Uri uri = data.getParcelableExtra("uri");

现在您可以使用此uri获取您要检索的任何信息。

希望这个答案有所帮助.. :)

答案 1 :(得分:0)

下面的代码定义了一个带有侦听器的简单ListView,该侦听器通过在参数中传递所选项来调用简单ViewPager

首先是清单:

public class SampleListFragment extends android.support.v4.app.ListFragment {

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

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

        final ArrayList<String> list = new ArrayList<String>();
        list.add("object1");
        list.add("object2");
        list.add("object3");

        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, list);
        getListView().setAdapter(adapter);

        getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                final String item = (String) adapterView.getItemAtPosition(i);

                // Quick and dirty way to call the ViewPager with the selected item
                final SampleViewPagerFragment sampleViewPagerFragment = SampleViewPagerFragment.newIntance(item);
                getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_holder, sampleViewPagerFragment).commit();

            }
        });
    }
}

接下来是ViewPager

public class SampleViewPagerFragment extends Fragment {

    public static SampleViewPagerFragment newIntance(String text){
        final SampleViewPagerFragment sampleViewPagerFragment = new SampleViewPagerFragment();
        final Bundle arguments = new Bundle();
        arguments.putString("object", text);
        sampleViewPagerFragment.setArguments(arguments);
        return sampleViewPagerFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_view_pager, null);

        final ViewPager viewPager = (ViewPager) view.findViewById(R.id.view_pager);
        final Bundle arguments = getArguments();

        if(arguments != null){
            // We create the adapter with arguments of the fragment
            final SampleAdapter adapter = new SampleAdapter(getChildFragmentManager(), (String) arguments.get("object"));
            viewPager.setAdapter(adapter);
        }

        return view;
    }

    private class SampleAdapter extends FragmentPagerAdapter {

        private String object;

        public SampleAdapter(FragmentManager fm, String object){
            super(fm);
            this.object = object;
        }

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

        @Override
        public Fragment getItem(int position) {
            // We pass the selected item in arguments
            return SampleFragment.newInstance(object + " " + position);
        }
    }
}

最后显示内容的片段:

public class SampleFragment extends Fragment {

    public static SampleFragment newInstance(String text){
        final SampleFragment sampleFragment = new SampleFragment();
        final Bundle arguments = new Bundle();
        arguments.putString("text", text);
        sampleFragment.setArguments(arguments);
        return sampleFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final TextView textView = new TextView(getActivity());

        final Bundle arguments = getArguments();
        if(arguments != null){
            textView.setText((String) arguments.get("text"));
        }

        return textView;
    }
}

我希望这就是你要找的......