web-dev-qa-db-fra.com

Forcer l'affichage de l'icône et du titre dans BottomNavigationView, android

Après avoir ajouté 4 éléments dans mon fichier menu.xml pour BottomNavigationView, il n’affiche que le titre de l’élément sélectionné et masque tous les autres titres ..__ Puis-je forcer l’affichage du titre et de l’icône. voici mon code. 

<?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" />
7
Abdelrhman Talat

Essayez ce code,

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>

Créez ce fichier dans le dossier 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);
    }
}

tout ce que vous devez faire est simplement de désactiver le mode Shift BottomNavigationView, en utilisant cette méthode dans votre code.

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");
        }
    }

appelez cette méthode comme ça,

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

        disableShiftMode(mBottomNav);

Cela fonctionnera. Je joins la capture d’écran ici,

 enter image description here

18
jeel raja

C'est simplement comme ça:

Kotlin

bottomNavigationView.labelVisibilityMode=LabelVisibilityMode.LABEL_VISIBILITY_LABELED

Java

bottomNavigationView.setLabelVisibilityMode(LabelVisibilityMode.LABEL_VISIBILITY_LABELED)
10

Au-dessus de celui-ci, je trouve une solution un peu plus longue à ce problème. J'ai eu une solution plus simple pour cela.

Ajoutez cette classe dans votre application:

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");
    }
}

}

puis ajoutez ceci dans votre activité où bottomnavigationview est disponible

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

Cela désactivera le mode de navigation de navigation et le texte et l'icône seront toujours affichés.

7
KishanSolanki124

après la bibliothèque de support 28.0.0, supportez LabelVisibilityMode.

xml config: app: labelVisibilityMode = "libellé"

 <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"/>

ou 

tu peux appeler :

BottomNavigationView.setLabelVisibilityMode(LabelVisibilityMode.LABEL_VISIBILITY_LABELED);
1
qinmiao

Cela fonctionne pour moi:

 navigation = (BottomNavigationView) view.findViewById(R.id.bottom_navigation);


     try{disableShiftMode(navigation);}catch(Exception ew){}

Créez cette méthode dans votre activité ou votre fragment où vous souhaitez appeler:

 @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) {

    }
}
0
Istiyak