334
技術社區[雲棲]
Android ActionBar 作為導航條的一個Bug
在Android兼容開發包(Support Package)的示例中,演示了ViewPager和ActionBar導航條一起使用的一個示例,該示例的代碼目錄位於:
android-sdk-windows\extras\android\support\v13\samples\Support13Demos
目錄中的
/Support13Demos/src/com/example/android/supportv13/app/ActionBarTabsPager.java
Java類中。
運行界麵如下:
如果修改其中的代碼,多添加一個ViewPager和Tab導航,當屏幕橫屏的時候則Tab導航會自動變為List導航。如下圖:
在這種List導航模式下 有個Bug,就是當左右滑動下麵的ViewPager的時候,上麵的List當前內容不變化,如下圖:
原因是如下的函數在List模型下沒有更改裏麵使用的Spinner的當前列表項:
mActionBar.setSelectedNavigationItem(position);
該Bug的修改方式見如下鏈接: https://android-review.googlesource.com/ 如果您無法修改Android係統的代碼,則可以通過如下的方式來解決該Bug:
@Override
public void onPageScrollStateChanged(int state) {
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
selectInSpinnerIfPresent(position, true);
}
/**
* Hack that takes advantage of interface parity between ActionBarSherlock and the native interface to reach inside
* the classes to manually select the appropriate tab spinner position if the overflow tab spinner is showing.
*
* Related issues: https://github.com/JakeWharton/ActionBarSherlock/issues/240 and
* https://android-review.googlesource.com/
*
* @author toulouse@crunchyroll.com
*/
private void selectInSpinnerIfPresent(int position, boolean animate) {
try {
View actionBarView = findViewById(R.id.abs__action_bar);
if (actionBarView == null) {
int id = getResources().getIdentifier("action_bar", "id", "android");
actionBarView = findViewById(id);
}
Class<?> actionBarViewClass = actionBarView.getClass();
Field mTabScrollViewField = actionBarViewClass.getDeclaredField("mTabScrollView");
mTabScrollViewField.setAccessible(true);
Object mTabScrollView = mTabScrollViewField.get(actionBarView);
if (mTabScrollView == null) {
return;
}
Field mTabSpinnerField = mTabScrollView.getClass().getDeclaredField("mTabSpinner");
mTabSpinnerField.setAccessible(true);
Object mTabSpinner = mTabSpinnerField.get(mTabScrollView);
if (mTabSpinner == null) {
return;
}
Method setSelectionMethod = mTabSpinner.getClass().getSuperclass().getDeclaredMethod("setSelection", Integer.TYPE, Boolean.TYPE);
setSelectionMethod.invoke(mTabSpinner, position, animate);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
注意:
-
You need to implement
OnPageChangeListener -
And set it in your viewPager:
viewPager.setOnPageChangeListener(this);(the fact that it's "this" is arbitrary) - Then use the code above (I'd appreciate the credit staying in there if you do use it)
原文轉載自 雲在千峰: https://yunfeng.sinaapp.com/?p=414
最後更新:2017-04-02 16:47:43


