在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/#/c/32492/ 如果您无法修改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/#/c/32492/ * * @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)
原文转载自 云在千峰: http://yunfeng.sinaapp.com/?p=414#ixzz1yseBE0al
时间: 2024-09-27 21:21:03