如何用代码更改BottomNavigationView的选定选项卡?(How to change selected tab of BottomNavigationView with code?)
无论如何,用代码从“com.android.support:design”库更改BottomNavigationView的选定选项卡?
<android.support.design.widget.BottomNavigationView xmlns:design="http://schema.android.com/apk/res/android.support.design" android:id="@+id/navigation" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" app:layout_anchorGravity="bottom" app:menu="@menu/bottom_bar" design:menu="@menu/bottom_bar"/>Is there anyway to change selected tab of BottomNavigationView from "com.android.support:design" library with code?
<android.support.design.widget.BottomNavigationView xmlns:design="http://schema.android.com/apk/res/android.support.design" android:id="@+id/navigation" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" app:layout_anchorGravity="bottom" app:menu="@menu/bottom_bar" design:menu="@menu/bottom_bar"/>最满意答案
看起来我们需要使用updateMenuView()方法更新BottomNavigaitonPresenter的状态。 带反射的代码示例;
bottomNavigationView.getMenu().getItem(3).setChecked(false); bottomNavigationView.getMenu().getItem(2).setChecked(false); bottomNavigationView.getMenu().getItem(1).setChecked(false); bottomNavigationView.getMenu().getItem(0).setChecked(true); try { final Field mPresenter = bottomNavigationView.getClass().getField("mPresenter"); mPresenter.setAccessible(true); final BottomNavigationPresenter presenter = (BottomNavigationPresenter) mPresenter.get(bottomNavigationView); presenter.updateMenuView(true); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); }Looks like we need to update BottomNavigaitonPresenter's state with updateMenuView() method. Example code with reflection;
bottomNavigationView.getMenu().getItem(3).setChecked(false); bottomNavigationView.getMenu().getItem(2).setChecked(false); bottomNavigationView.getMenu().getItem(1).setChecked(false); bottomNavigationView.getMenu().getItem(0).setChecked(true); try { final Field mPresenter = bottomNavigationView.getClass().getField("mPresenter"); mPresenter.setAccessible(true); final BottomNavigationPresenter presenter = (BottomNavigationPresenter) mPresenter.get(bottomNavigationView); presenter.updateMenuView(true); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); }更多推荐
发布评论