7

我有一個使用ViewPager + actionbar Sherlock標籤的屏幕。我對呼機setOnPageChangeListener集,並執行以下操作:Actionbar Sherlock - 標籤在橫向滑動時不會改變風景

@Override 
public void onPageSelected(final int position) { 
    actionBar.setSelectedNavigationItem(position); 
} 

這工作在縱向模式下,甚至在景觀,如果我只有幾個標籤並顯示所有選項卡就好了。但是,如果我在橫向添加更多選項卡,這些選項卡會合併到一個下拉小部件中。當我瀏覽ViewPager時,將執行setSelectedNavigationItem方法,但現在它對下拉選擇沒有影響:它保持在最後選定的值。這是非常糟糕的,因爲用戶缺少視覺線索:標籤可能會說「一」,但用戶已經在頁面#6。

有沒有辦法以編程方式更改基於位置顯示哪個選項卡?

P.S.我知道爲什麼發生這種情況: 這裏的代碼com.android.internal.app.ActionBarImpl:

public void setSelectedNavigationItem(int position) { 
    switch (mActionView.getNavigationMode()) { 
    case NAVIGATION_MODE_TABS: 
     selectTab(mTabs.get(position)); 
     break; 
    case NAVIGATION_MODE_LIST: 
     mActionView.setDropdownSelectedPosition(position); 
     break; 
    default: 
     throw new IllegalStateException(
       "setSelectedNavigationIndex not valid for current navigation mode"); 
    } 
} 

當我經過那一步,我可以看到導航模式仍然NAVIGATION_MODE_TABS雖然標籤顯示爲列表。現在 - 我的膝蓋混亂反應是將代碼放入onConfigurationChanged以適當地設置導航模式,但不應該自動發生?

P.P.S.還有的Android bug申請它已經包含該補丁

回答

11

基地問題(請參閱PPS)這裏的解決方法確實有效。只需將其添加到您的尋呼機上即可。

mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() 
    { 
     @Override 
     public void onPageSelected(int position) 
     { 
      actionBar.getTabAt(position).select(); 
      ViewParent root = findViewById(android.R.id.content).getParent(); 
      findAndUpdateSpinner(root, position); 
     } 

     /** 
     * Searches the view hierarchy excluding the content view 
     * for a possible Spinner in the ActionBar. 
     * 
     * @param root The parent of the content view 
     * @param position The position that should be selected 
     * @return if the spinner was found and adjusted 
     */ 
     private boolean findAndUpdateSpinner(Object root, int position) 
     { 
      if (root instanceof android.widget.Spinner) 
      { 
       // Found the Spinner 
       Spinner spinner = (Spinner) root; 
       spinner.setSelection(position); 
       return true; 
      } 
      else if (root instanceof ViewGroup) 
      { 
       ViewGroup group = (ViewGroup) root; 
       if (group.getId() != android.R.id.content) 
       { 
       // Found a container that isn't the container holding our screen layout 
       for (int i = 0; i < group.getChildCount(); i++) 
       { 
        if (findAndUpdateSpinner(group.getChildAt(i), position)) 
        { 
         // Found and done searching the View tree 
         return true; 
        } 
       } 
       } 
      } 
      // Nothing found 
      return false; 
     } 
    }); 
+0

此解決方案適用於本機ActionBar,但不適用於兼容性(在薑餅模擬器上)。這怎麼能解決呢? –

+0

謝謝!這絕對有效:-) –

+0

謝謝!最後找到了一個工作解 – Ahmad

0

您需要在文件中添加一些代碼在ActionBarSherlock庫項目(ActionBarImpl.java)上看到Android的錯誤,我引用了this link

+0

您指出的修復程序不起作用,我只是檢查了它。該代碼只從onConfigurationChanged調用,但我需要選中選項卡更改時,我從頁面頁面之間 – Bostone

+0

如果您使用ViewPager比在其監聽器內,您需要顯式設置選定的選項卡...這是我在做的一個我的項目。 – aProgrammer