2012-03-16 28 views
9

Tengo un adaptador que amplía FragmentPagerAdapter y aprovecha el estilo de ICS actionBar. Esta barra de acciones tiene acciones que toman entrada de la página seleccionada actualmente.cómo obtener la posición actual en FragmentPagerAdapter?

Específicamente, tengo un icono de captura de pantalla en la barra de acciones que toma la url de la página actual y muestra capturas de pantalla de esa url. Sin embargo, no sé cómo recuperar la página seleccionada actualmente.

¿Cómo puedo poner en práctica algo así como un

public int getActivePage() { 
     return position; 

Im sigue trabajando en la implementación ViewPager, por lo que mi código es todavía muy dependiente de ejemplos, por lo desatender el desorden: P

Las áreas problemáticas marcado a continuación.

public class ListFragmentViewPagerActivity extends FragmentActivity { 
ArrayList<String> URLS; 
ArrayList<String> TITLES; 
BroadcastReceiver receiver; 
String threadTitle = null; 
public static String threadUrl = null; 
String type = null; 
String threadAuthor = null; 
String ident = null; 
boolean isFav = false; 
String author = null; 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.thread_view); 

    Bundle extras = getIntent().getExtras(); 
    threadTitle = extras.getString("title"); 
    threadUrl = extras.getString("url"); 
    type = extras.getString("type"); 
    ident = extras.getString("ident"); 
    author = extras.getString("author"); 
    try { 
     URLS = extras.getStringArrayList("urls"); 
     TITLES = extras.getStringArrayList("titles"); 
    } catch (Exception e) { 
     URLS = null; 
    }   

    final FDBAdapter db = new FDBAdapter(this); 
    db.open(); 
    Cursor c = db.getAllFavs(); 
    if (c.getCount()>0) { 
     if (c.getString(2).equals(threadTitle)) { 
      isFav = true; 
     } 
      try { 
       while (c.moveToNext()) { 
        Log.d("FAVS", c.getString(2)); 
        if (c.getString(2).equals(threadTitle)) { 
         isFav = true; 
        } 
       } 
      } catch (Exception ep) { 
       ep.printStackTrace(); 
      } 
    } 
    c.close(); 
    db.close(); 

    ViewPager pager = (ViewPager) findViewById(android.R.id.list); 
    pager.setAdapter(new ExamplePagerAdapter(getSupportFragmentManager())); 
    TitlePageIndicator indicator = (TitlePageIndicator)findViewById(R.id.indicator); 
    indicator.setViewPager(pager); 

    receiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 
      if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { 
       long downloadId = intent.getLongExtra(
         DownloadManager.EXTRA_DOWNLOAD_ID, 0); 

       String ns = Context.NOTIFICATION_SERVICE; 
       NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns); 

       int icon = R.drawable.ic_launcher;  // icon from resources 
       CharSequence tickerText = "Download ready!";    // ticker-text 
       long when = System.currentTimeMillis();   // notification time 
       CharSequence contentTitle = "OMG"; // expanded message title 
       CharSequence contentText = "Your download is finished!";  // expanded message text 

       Intent notificationIntent = new Intent(context, ExampleListFragment.class); 

       PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); 

       Notification notification = new Notification(icon, tickerText, when); 
       notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); 
       notification.defaults |= Notification.DEFAULT_VIBRATE; 
       notification.flags |= Notification.FLAG_AUTO_CANCEL; 
       final int HELLO_ID = 1; 

       mNotificationManager.notify(HELLO_ID, notification); 
      } 
     } 
}; 

registerReceiver(receiver, new IntentFilter(
     DownloadManager.ACTION_DOWNLOAD_COMPLETE)); 

} 

public class ExamplePagerAdapter extends FragmentPagerAdapter implements TitleProvider{ 

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

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

    @Override 
    public Fragment getItem(int position) { 
     Fragment fragment = new ExampleListFragment(); 

     // set arguments here, if required 
     Bundle args = new Bundle(); 
     args.putString("url", URLS.get(position)); 
     fragment.setArguments(args); 

     return fragment; 
    } 

    @Override 
    public String getTitle(int pos) { 
     return TITLES.get(pos); 
    } 

} 

public boolean onCreateOptionsMenu(Menu menu) { 
    MenuInflater menuinflate = new MenuInflater(this); 
    menuinflate.inflate(R.menu.thread_menu, menu); 
    if (type.equals("xda")) { 
     menu.removeItem(R.id.ss_view); 
    } 
    if (isFav) { 
     menu.getItem(2).setIcon(R.drawable.fav_ab); 
    } 
    return true;   
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 

    switch (item.getItemId()) { 
     case android.R.id.home: 
      Intent intent = new Intent(this, MainActivity.class); 
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
      startActivity(intent); 
     break; 
     case R.id.ss_view: 
      Intent ssi = new Intent(this, SSActivity.class); 
      ssi.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
      Bundle b = new Bundle(); 

//I need to get the position of the currently active page here so that I can retrieve the //corresponding values for the title and url. 
       b.putString("title", threadTitle); 
       b.putString("url", threadUrl); 
       ssi.putExtras(b); 
       startActivity(ssi); 
      break; 
      case R.id.restart: 
      break; 
      case R.id.fav_ab: 
       threadUrl = new String(threadUrl.replaceAll("http://", "")); 
       FDBAdapter fdb = new FDBAdapter(this); 
       fdb.open();    
       if (isFav) { 
        Cursor c = fdb.getAllUrls(); 
         while (c.moveToNext()) { 
          String id = c.getString(c.getColumnIndex("_id")); 
          int rowId = Integer.parseInt(id); 
          if(c.getString(c.getColumnIndex("url")).equals(threadUrl)) { 
           if (fdb.deleteUrl(rowId)) { 
            Log.d("THREAD", "SUCCESS"); 
           } else { 
            Log.d("THREAD", "FAILED"); 
           } 
          } 
        } 
        c.close(); 
        item.setIcon(R.drawable.fav_ab_off); 
        isFav = false; 
       } else { 
        fdb.insertFav(threadUrl, threadTitle, ident, type, author, "thread"); 
        item.setIcon(R.drawable.fav_ab); 
        isFav = true; 
       } 
       fdb.close(); 
      default: 
       return super.onOptionsItemSelected(item); 
     } 
     return false; 
    } 

    @Override 
    public void onStop() { 
     super.onStop(); 
     unregisterReceiver(receiver);  
    } 

    @Override 
    public void onStart() { 
     super.onStart(); 
     registerReceiver(receiver, new IntentFilter(
       DownloadManager.ACTION_DOWNLOAD_COMPLETE)); 
    } 

} 

Heres lo que quiero decir con la página actualmente seleccionada.

enter image description here

Respuesta

18

Creo que lo que busca es onPageChangedListener(). Este método pertenece al TitlePageIndicator. Algo así como ...

indicator.setOnPageChangedListener(new OnPageChangedListener() { 
// Implement unimplemented methods... 
}); 
+0

¿cómo puedo devolver la posición actual con esto? – r2DoesInc

+1

Esta interfaz le proporciona la posición en la que está la página actual. El código de implementación completo es ... http://pastebin.com/FTbikKW9 –

+0

exactamente lo que necesitaba. ¡Gracias! – r2DoesInc

Cuestiones relacionadas