0

即時通訊工作在一個關於處理飼料的小項目即時通訊尋找在列表視圖中處理飼料和在viewpager中顯示細節,並獲得相同的飼料當我點擊列表視圖我失去了我可以通過光標位置到viewpaver從列表視圖傳遞光標位置到viewpager

它S上的結束於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); 
       } 
      }); 
     } 
    }; 


    } 

它S中的片段細節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(); 
       } 
      } 
     }; 

    } 

回答

0

以下是我從一個活動通過我的URI與另一個:

後你從你的onListItemClick的URI,加入這行代碼之後:

String uriString = uri.toString(); 

現在,你可以做到這一點通過共享的偏好或通過從意圖傳遞演員,

方法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:

第一:在你的活動,你所得到的是開放的,

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獲取您嘗試檢索的任何信息。

希望這個答案可以幫助.. :)

+0

但我認爲Uti將只有點擊位置!不是所有的飼料! – user3376584

+0

True ..在那種情況下,你是否試圖在viewpager中獲取光標,你可以根據你的列表視圖位置設置提要? – mike20132013

+0

我很抱歉..我只是不清楚你的問題。 – mike20132013

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; 
    } 
} 

我希望這是你在找什麼..

+0

是的,但它是如何綁定viewpager片段中的光標位置並將其移動到特定位置 – user3376584