2012-03-16 7 views
9

У меня есть адаптер, который расширяет FragmentPagerAdapter и использует ICS-стиль actionBar. Эта панель действий содержит действия, которые вводят ввод с текущей выбранной страницы.Как получить текущую позицию в FragmentPagerAdapter?

В частности, у меня есть значок скриншота в панели действий, который берет URL-адрес текущей страницы и отображает скриншоты с этого URL-адреса. Однако я не знаю, как извлечь текущую выбранную страницу.

Как я могу реализовать нечто вроде

public int getActivePage() { 
     return position; 

Im все еще работает над реализацией ViewPager, поэтому мой код по-прежнему сильно зависит от примеров, поэтому игнорировать беспорядок: P

проблемные районы отмечено ниже.

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, что я имею ввиду по выбранной на данный момент странице.

enter image description here

ответ

18

Я считаю, что вы ищете onPageChangedListener(). Этот метод принадлежит TitlePageIndicator. Что-то вроде ...

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

Как бы я мог вернуть текущую позицию с этим? – r2DoesInc

+1

Этот интерфейс предоставляет вам позицию, в которой находится текущая страница. Полный код реализации ... http://pastebin.com/FTbikKW9 –

+0

именно то, что мне нужно. благодаря! – r2DoesInc

Смежные вопросы