如何用代码更改BottomNavigationView的选定选项卡?(How to change selected tab of BottomNavigationView with code?)

编程入门 行业动态 更新时间:2024-10-24 12:20:19
如何用代码更改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(); }

更多推荐

本文发布于:2023-07-06 07:28:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1047329.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何用   选项卡   代码   BottomNavigationView   code

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!