【问题标题】:Force showing icon and title in BottomNavigationView support android强制在BottomNavigationView中显示图标和标题支持android
【发布时间】:2016-12-27 22:25:05
【问题描述】:

在我的 menu.xml 文件中为 BottomNavigationView 添加 4 个项目后,它只显示选定的项目标题并隐藏所有其他标题。 我可以强制显示标题和图标吗? 这是我的代码。

<?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/action_home"
    android:enabled="true"
    android:icon="@drawable/ic_home_24dp"
    android:title="@string/text_home"
    app:showAsAction="ifRoom" />

<item
    android:id="@+id/action_category"
    android:enabled="true"
    android:icon="@drawable/ic_grid_24dp"
    android:title="@string/text_category"
    app:showAsAction="ifRoom" />

<item
    android:id="@+id/action_me"
    android:enabled="true"
    android:icon="@drawable/ic_me_24dp"
    android:title="@string/text_me"
    app:showAsAction="ifRoom" />

<item
    android:id="@+id/action_setting"
    android:enabled="true"
    android:icon="@drawable/ic_cog_24dp"
    android:title="@string/text_setting"
    app:showAsAction="ifRoom" />
</menu>

<android.support.design.widget.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:background="@android:color/white"
    android:elevation="6dp"
    android:translationZ="6dp"
    app:menu="@menu/bottom_navigation_main" />

【问题讨论】:

    标签: android android-layout bottomnavigationview


    【解决方案1】:

    就是这样:

    科特林

    bottomNavigationView.labelVisibilityMode=LabelVisibilityMode.LABEL_VISIBILITY_LABELED
    

    Java

    bottomNavigationView.setLabelVisibilityMode(LabelVisibilityMode.LABEL_VISIBILITY_LABELED)
    

    【讨论】:

    • 伟大的一班轮解决方案,而不会失去换档效果。
    • 在 BottomNavigationView 中找不到 setLabelVisibilityMode 方法?
    • 尝试支持库 28.0.0-alpha1
    • 是的,仍然不能在 API 27 或更高版本中使用
    • 不能在 API 26 中使用
    【解决方案2】:

    试试这个代码,

    activity_main.xml:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:design="http://schemas.android.com/apk/res-auto"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="com.segunfamisa.sample.bottomnav.MainActivity">
    
        <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="#f1f1f1">
    
        </FrameLayout>
    
        <android.support.design.widget.BottomNavigationView
            android:id="@+id/navigation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="start"
            design:menu="@menu/bottom_nav_items" />
    </LinearLayout>
    

    fragment_menu.xml:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/fragment_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.segunfamisa.sample.bottomnav.MenuFragment">
    
        <TextView
            android:id="@+id/text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:textColor="@android:color/white"
            android:gravity="center"
            />
    
    </RelativeLayout>
    

    将此文件放入 menu 文件夹中,

    bottom_nav_items.xml

    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    
        <item
            android:id="@+id/action_home"
            android:enabled="true"
            android:icon="@android:drawable/ic_dialog_map"
            android:title="One"
            app:showAsAction="ifRoom"/>
        <item
            android:id="@+id/action_category"
            android:enabled="true"
            android:icon="@android:drawable/ic_dialog_info"
            android:title="Two"
            app:showAsAction="ifRoom"/>
        <item
            android:id="@+id/action_me"
            android:enabled="true"
            android:icon="@android:drawable/ic_dialog_email"
            android:title="Three"
            app:showAsAction="ifRoom"/>
        <item
            android:id="@+id/action_setting"
            android:enabled="true"
            android:icon="@android:drawable/ic_popup_reminder"
            android:title="Four"
            app:showAsAction="ifRoom"/>
    </menu>
    

    MainActivity.java:

       public class MainActivity extends AppCompatActivity {
        private static final String SELECTED_ITEM = "arg_selected_item";
    
        private BottomNavigationView mBottomNav;
        private int mSelectedItem;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            mBottomNav = (BottomNavigationView) findViewById(R.id.navigation);
    
            disableShiftMode(mBottomNav);
            mBottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    selectFragment(item);
                    return true;
                }
            });
    
            MenuItem selectedItem;
            if (savedInstanceState != null) {
                mSelectedItem = savedInstanceState.getInt(SELECTED_ITEM, 0);
                selectedItem = mBottomNav.getMenu().findItem(mSelectedItem);
            } else {
                selectedItem = mBottomNav.getMenu().getItem(0);
            }
            selectFragment(selectedItem);
        }
    
        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) {
                //Timber.e(e, "Unable to get shift mode field");
            } catch (IllegalAccessException e) {
                //Timber.e(e, "Unable to change value of shift mode");
            }
        }
    
    
        @Override
        protected void onSaveInstanceState(Bundle outState) {
            outState.putInt(SELECTED_ITEM, mSelectedItem);
            super.onSaveInstanceState(outState);
        }
    
        @Override
        public void onBackPressed() {
            MenuItem homeItem = mBottomNav.getMenu().getItem(0);
            if (mSelectedItem != homeItem.getItemId()) {
                // select home item
                selectFragment(homeItem);
            } else {
                super.onBackPressed();
            }
        }
    
        private void selectFragment(MenuItem item) {
            Fragment frag = null;
            // init corresponding fragment
            switch (item.getItemId()) {
                case R.id.action_home:
                    frag = MenuFragment.newInstance(getString(R.string.text_home),
                            getColorFromRes(R.color.color_home));
                    break;
                case R.id.action_category:
                    frag = MenuFragment.newInstance(getString(R.string.text_notifications),
                            getColorFromRes(R.color.color_notifications));
                    break;
                case R.id.action_me:
                    frag = MenuFragment.newInstance(getString(R.string.text_search),
                            getColorFromRes(R.color.color_search));
                    break;
                case R.id.action_setting:
                    frag = MenuFragment.newInstance(getString(R.string.text_home),
                            getColorFromRes(R.color.color_home));
                    break;
            }
    
            // update selected item
            mSelectedItem = item.getItemId();
    
            // uncheck the other items.
            for (int i = 0; i < mBottomNav.getMenu().size(); i++) {
                MenuItem menuItem = mBottomNav.getMenu().getItem(i);
                menuItem.setChecked(menuItem.getItemId() == item.getItemId());
            }
    
            updateToolbarText(item.getTitle());
    
            if (frag != null) {
                FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                ft.add(R.id.container, frag, frag.getTag());
                ft.commit();
            }
        }
    
        private void updateToolbarText(CharSequence text) {
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.setTitle(text);
            }
        }
    
        private int getColorFromRes(@ColorRes int resId) {
            return ContextCompat.getColor(this, resId);
        }
    

    MenuFragment.java:

    public class MenuFragment extends Fragment {
        private static final String ARG_TEXT = "arg_text";
        private static final String ARG_COLOR = "arg_color";
    
        private String mText;
        private int mColor;
    
        private View mContent;
        private TextView mTextView;
    
        public static Fragment newInstance(String text, int color) {
            Fragment frag = new MenuFragment();
            Bundle args = new Bundle();
            args.putString(ARG_TEXT, text);
            args.putInt(ARG_COLOR, color);
            frag.setArguments(args);
            return frag;
        }
    
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            return inflater.inflate(R.layout.fragment_menu, container, false);
        }
    
        @Override
        public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
    
            // retrieve text and color from bundle or savedInstanceState
            if (savedInstanceState == null) {
                Bundle args = getArguments();
                mText = args.getString(ARG_TEXT);
                mColor = args.getInt(ARG_COLOR);
            } else {
                mText = savedInstanceState.getString(ARG_TEXT);
                mColor = savedInstanceState.getInt(ARG_COLOR);
            }
    
            // initialize views
            mContent = view.findViewById(R.id.fragment_content);
            mTextView = (TextView) view.findViewById(R.id.text);
    
            // set text and background color
            mTextView.setText(mText);
            mContent.setBackgroundColor(mColor);
        }
    
        @Override
        public void onSaveInstanceState(Bundle outState) {
            outState.putString(ARG_TEXT, mText);
            outState.putInt(ARG_COLOR, mColor);
            super.onSaveInstanceState(outState);
        }
    }
    

    你需要做的只是禁用BottomNavigationView Shift模式, 在你的代码中使用这个方法。

    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) {
                //Timber.e(e, "Unable to get shift mode field");
            } catch (IllegalAccessException e) {
                //Timber.e(e, "Unable to change value of shift mode");
            }
        }
    

    像这样调用这个方法,

    mBottomNav = (BottomNavigationView) findViewById(R.id.navigation);
    
            disableShiftMode(mBottomNav);
    

    它会起作用的。我在这里附上截图,

    【讨论】:

    【解决方案3】:

    支持库28.0.0后,支持LabelVisibilityMode。

    xml 配置:app:labelVisibilityMode="labeled"

     <android.support.design.widget.BottomNavigationView
              android:id="@+id/bottom_navigation"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:layout_margin="0dp"
              android:background="?bottom_tint_color"
              app:elevation="@dimen/padding_4"
              app:labelVisibilityMode="labeled"
              app:itemIconTint="?drawer_tint_color"
              app:itemTextColor="?drawer_tint_color"
              app:menu="@menu/bottom_navigation_lite"/>
    

    你可以打电话:

    BottomNavigationView.setLabelVisibilityMode(LabelVisibilityMode.LABEL_VISIBILITY_LABELED);
    

    【讨论】:

      【解决方案4】:

      在上面,我找到了一个更长的解决方案来解决这个问题。我有一个更简单的解决方案。

      在您的应用中添加此类:

      class BottomNavigationViewHelper {
      
      @SuppressLint("RestrictedApi")
      public 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);
                  // set once again checked value, so view will be updated
                  item.setChecked(item.getItemData().isChecked());
              }
      
          } 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");
          }
      }
      

      }

      然后将其添加到您的活动中,其中底部导航视图可用

      BottomNavigationViewHelper.removeShiftMode(bottomNavigationView);//disable BottomNavigationView shift mode
      

      这将禁用导航视图的移动模式,并且将始终显示文本和图标。

      【讨论】:

        【解决方案5】:

        从支持库 28-alpha 开始,我们可以在 BottomNavigation 组件上使用app:labelVisibilityMode 属性。我们可以使用的值,有labeledunlabeledselectedauto

        • labeled 将保持所有标签可见。
        • unlabeled 将只显示图标。
        • selected 将只显示所选项目的标签和班次 项目。
        • auto会根据我们的商品数量选择labeled或者selected 已标记 1-3 项并选择 3 项以上。

        这是使用它的一些例子:

        <android.support.design.widget.BottomNavigationView
                android:id="@+id/mainBottomNav"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                app:elevation="@dimen/dimen_8dp"
                app:menu="@menu/bottom_menu"
                app:labelVisibilityMode="labeled"/>
        

        【讨论】:

          【解决方案6】:

          这对我有用:

           navigation = (BottomNavigationView) view.findViewById(R.id.bottom_navigation);
          
          
               try{disableShiftMode(navigation);}catch(Exception ew){}
          

          在您要调用的 Activity 或 Fragment 中创建此方法:

           @SuppressLint("RestrictedApi")
          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);
          
                      item.setChecked(item.getItemData().isChecked());
                  }
              } catch (NoSuchFieldException e) {
          
              } catch (IllegalAccessException e) {
          
              }
          }
          

          【讨论】:

            猜你喜欢
            • 2021-11-17
            • 1970-01-01
            • 1970-01-01
            • 2017-03-16
            • 1970-01-01
            • 2020-04-18
            • 2020-10-26
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多