BottomNavigationView - How to uncheck all MenuItems and keep Titles being displayed?

你离开我真会死。 提交于 2019-11-28 02:53:54

问题


As I liked the design from BottomNavigationView I decided to implement a new Menu for my App with it, instead of just using simple buttons.

I took this post as a guideline.

According to BottomNavigationView's documentation, its purpose is to

provide quick navigation between top-level views of an app. It is primarily designed for use on mobile.

In my case, I just want each MenuItem to launch an activity, but by default there is always one MenuItem selected:

I tried to set the color to white with:

app:itemIconTint="@color/white" app:itemTextColor="@color/white" 

Still, visibly selected MenuItem is different from others (Title size bigger), which is still bothering me:

I came with the idea to place a hidden MenuItem to select like:

<item android:id="@+id/uncheckedItem" android:title="" /> 

and make its view GONE:

 bottomNavigationView.getMenu().findItem(R.id.uncheckedItem).setChecked(true);  bottomNavigationView.findViewById(R.id.uncheckedItem).setVisibility(View.GONE); 

This makes all MenuItems unchecked, but by default BottomNavigationView is hidding Titles, as it has more than 3 MenuItems to display, even if the fourth MenuItem is settle to GONE:

So my question remains, is there away/hack to unselect all MenuItems and keep its titles being displayed?


回答1:


mNavigationBottom.getMenu().setGroupCheckable(0, false, true); 



回答2:


Thanks for your idea. I have implement it in my lib. I have a better way do it by reflect. So it won't show space.

If you have interest. Click here : https://github.com/ittianyu/BottomNavigationViewEx

private void initBottomViewAndLoadFragments(final BottomNavigationViewEx bnve) {     bnve.enableAnimation(false);     bnve.enableShiftingMode(false);     bnve.enableItemShiftingMode(false);      // use the unchecked color for first item     bnve.setIconTintList(0, getResources().getColorStateList(R.color.bnv_unchecked_black));     bnve.setTextTintList(0, getResources().getColorStateList(R.color.bnv_unchecked_black));      bnve.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {          private boolean firstClick = true;         private int lastItemId = -1;          @Override         public boolean onNavigationItemSelected(@NonNull MenuItem item) {             // restore the color when click             if (firstClick) {                 firstClick = false;                 bnve.setIconTintList(0, getResources().getColorStateList(R.color.selector_bnv));                 bnve.setTextTintList(0, getResources().getColorStateList(R.color.selector_bnv));             }              if (firstClick || lastItemId == -1 || lastItemId != item.getItemId()) {                 lastItemId = item.getItemId();             } else {                 return false;             }              // do stuff             return fillContent(item.getItemId());         }     }); } 

-- res/color/selector_bnv.xml

<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android">     <item android:color="@color/bnv_checked_white" android:state_checked="true" />     <item android:color="@color/bnv_unchecked_black" /> </selector> 

-- res/values/colors.xml

<color name="bnv_checked_white">@android:color/white</color> <color name="bnv_unchecked_black">@android:color/black</color> 



回答3:


To unselect all items I have create this extension:

fun BottomNavigationView.uncheckAllItems() {     menu.setGroupCheckable(0, true, false)     for (i in 0 until menu.size()) {         menu.getItem(i).isChecked = false     }     menu.setGroupCheckable(0, true, true) } 

menu.setGroupCheckable(0, true, false) make it possible. The third parameter made the menu not exclusive and then within the loop you change the checked status. To finish set the menu to exclusive again.

Here the doc




回答4:


I found my own solution merging my progress with this post.

Steps:

  1. Update proguard-rules.pro and sync build
  2. Create Helper to disable BottomNavigationView Shift Mode
  3. Create an Item to hide on Menu.xml
  4. Inflate BottomNavigationView
  5. Set Item to be hidden as Checked GONE
  6. Use Helper to disable Shifting Mode

Output:

Working code:

proguard-rules.pro:

-keepclassmembers class android.support.design.internal.BottomNavigationMenuView {     boolean mShiftingMode; } 

BottomNavigationShiftHelper.java:

public class BottomNavigationShiftHelper {      private final static String TAG = "DEBUG_BOTTOM_NAV_UTIL";      public static void disableShiftMode(BottomNavigationView view) {         BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);         try {             Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");             shiftingMode.setAccessible(true);             shiftingMode.setBoolean(menuView, false);             shiftingMode.setAccessible(false);             for (int i = 0; i < menuView.getChildCount(); i++) {                 BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);                 item.setShiftingMode(false);                 // set once again checked value, so view will be updated                 item.setChecked(item.getItemData().isChecked());             }         } catch (NoSuchFieldException e) {             Log.d(TAG, "Unable to get shift mode field");         } catch (IllegalAccessException e) {             Log.d(TAG, "Unable to change value of shift mode");         }     } } 

Activity Sample.java:

 private void loadNavigationBar() {         BottomNavigationView bottomNavigationView = (BottomNavigationView)                 findViewById(R.id.navigation_bar);          bottomNavigationView.getMenu().findItem(R.id.uncheckedItem).setChecked(true);         bottomNavigationView.findViewById(R.id.uncheckedItem).setVisibility(View.GONE);          BottomNavigationViewUtils.disableShiftMode(bottomNavigationView);          bottomNavigationView.setOnNavigationItemSelectedListener(                 new BottomNavigationView.OnNavigationItemSelectedListener() {                     @Override                     public boolean onNavigationItemSelected(@NonNull MenuItem item) {                         switch (item.getItemId()) {                             case R.id.newList:                                 //Do The Math                                 break;                             case R.id.loadList:                                 //Do The Math                                 break;                             case R.id.settings:                                 //Do The Math                                 break;                         }                         return false;                     }                 });     } 

BottomNavigationMenu.xml:

<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto">     <item         android:id="@+id/newList"         android:enabled="true"         android:icon="@drawable/new_list"         android:title="@string/common.button.list.new"         app:showAsAction="withText" />     <item         android:id="@+id/loadList"         android:enabled="true"         android:icon="@drawable/load"         android:title="@string/common.button.list.load"         app:showAsAction="withText" />     <item         android:id="@+id/settings"         android:enabled="true"         android:icon="@drawable/settings"         android:title="@string/common.label.settings"         app:showAsAction="withText" />     <item         android:id="@+id/uncheckedItem"         android:title="" /> </menu> 

BottomNavigationComponent (inside Activity.xml):

<android.support.design.widget.BottomNavigationView     android:id="@+id/navigation_bar"     android:layout_width="fill_parent"     android:layout_height="wrap_content"     app:itemIconTint="@color/white"     app:itemTextColor="@color/white"     android:background="@drawable/BottomNavigationMenu.xml"     app:menu="@menu/supercart_bottom_navigation" /> 



回答5:


Your solution seems change the space between items

There is my solution :

"Just set color of clicked same as color of un-clicked."

for example:

private void changeMenuItemCheckedStateColor(BottomNavigationView bottomNavigationView, String checkedColorHex, String uncheckedColorHex) {     int checkedColor = Color.parseColor(checkedColorHex);     int uncheckedColor = Color.parseColor(uncheckedColorHex);      int[][] states = new int[][] {             new int[] {-android.R.attr.state_checked}, // unchecked             new int[] {android.R.attr.state_checked}, // checked      };      int[] colors = new int[] {             uncheckedColor,             checkedColor     };      ColorStateList colorStateList = new ColorStateList(states, colors);      bottomNavigationView.setItemTextColor(colorStateList);     bottomNavigationView.setItemIconTintList(colorStateList);  } 

if you want to un-check all items, you can

changeMenuItemCheckedStateColor(mBottomNavigationView, "#999999", "#999999"); 

if you want to restore the color setting, you can

changeMenuItemCheckedStateColor(mBottomNavigationView, "FF743A", "999999"); 



回答6:


This is the same as the accepted answer except I have changed two lines of code marked below. When looping through the BottomNavigationItemViews, I set checked to false always and I also set checkable to false. This prevents the Menu Items from changing size. You still need this proguard rule:

      -keepclassmembers class android.support.design.internal.BottomNavigationMenuView {          boolean mShiftingMode;       } 

Updated code:

    static void removeShiftMode(BottomNavigationView view)     {         BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);         try         {             Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");             shiftingMode.setAccessible(true);             shiftingMode.setBoolean(menuView, false);             shiftingMode.setAccessible(false);             for (int i = 0; i < menuView.getChildCount(); i++)             {                 BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);                 item.setShiftingMode(false);                 item.setChecked(false); // <--- This line changed                 item.setCheckable(false);  // <-- This line was added             }         }         catch (NoSuchFieldException e)         {             Log.e("ERROR NO SUCH FIELD", "Unable to get shift mode field");         }         catch (IllegalAccessException e)         {             Log.e("ERROR ILLEGAL ALG", "Unable to change value of shift mode");         }     } 



回答7:


The best answer mNavigationBottom.getMenu().setGroupCheckable(0, false, true) did not work for me. It still showed the first item as being selected.

What did work for me is to have an invisible item and to select that, exactly like you did in the question.

Add app:labelVisibilityMode="labeled" to your BottomNavigationView so that all items remain in view with their titles.




回答8:


There is an exception in accepted answer which we set maximum item we cant implement that code.So I got a code that is more simple than accepted code and it's also working with maximum item.

I referred from here Custom TextSize of BottomNavigationView support android

In your dimen.xml you can put:

<dimen name="design_bottom_navigation_text_size" tools:override="true">10sp</dimen> <dimen name="design_bottom_navigation_active_text_size" tools:override="true">10sp</dimen> 

Doing this you are overriding the default value of dimen that the internal classes of BottomNavigationView use. So be carreful.

Set this code in your onCreate method where the bottom navigation view initialized

mNavigationBottom.getMenu().setGroupCheckable(0, false, true); 

and Last set your bottom navigation bar like this :

 <com.google.android.material.bottomnavigation.BottomNavigationView     android:id="@+id/nav_view"     android:layout_width="match_parent"     android:layout_height="?attr/actionBarSize"     android:layout_gravity="bottom"     android:background="?android:attr/windowBackground"     android:fitsSystemWindows="true"     app:labelVisibilityMode="labeled"     app:layout_anchorGravity="fill"     app:menu="@menu/bottom_nav_menu" /> 

In this set your app:labelVisibilityMode to labeled



来源:https://stackoverflow.com/questions/41372293/bottomnavigationview-how-to-uncheck-all-menuitems-and-keep-titles-being-displa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!