webentwicklung-frage-antwort-db.com.de

Erzwingen Sie die Anzeige von Symbol und Titel in Android-Unterstützung von BottomNavigationView

Nach dem Hinzufügen von 4 Elementen in meiner menu.xml-Datei für BottomNavigationView wird nur der ausgewählte Elementtitel angezeigt und alle anderen Titel ausgeblendet. Kann ich die Anzeige des Titels und des Symbols erzwingen? hier ist mein 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

Versuchen Sie diesen 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>

Erstellen Sie diese Datei im Ordner 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);
    }
}

alles, was Sie tun müssen, ist deaktivieren Sie den BottomNavigationView Shift-Modus, mit dieser Methode in Ihrem 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");
        }
    }

nenne diese Methode so,

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

        disableShiftMode(mBottomNav);

Es wird funktionieren. Ich füge Screenshot hier an,

 enter image description here

18
jeel raja

Es ist einfach so:

Kotlin

bottomNavigationView.labelVisibilityMode=LabelVisibilityMode.LABEL_VISIBILITY_LABELED

Java

bottomNavigationView.setLabelVisibilityMode(LabelVisibilityMode.LABEL_VISIBILITY_LABELED)
10

Oberhalb finde ich eine etwas längere Lösung für dieses Problem. Ich hatte eine einfachere Lösung dafür.

Fügen Sie diese Klasse Ihrer App hinzu:

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

}

fügen Sie dies dann in Ihre Aktivität ein, wenn bottomnavigationview verfügbar ist

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

Dadurch wird der Verschiebemodus der Navigationsansicht deaktiviert und Text und Symbol werden immer angezeigt.

7

nach der Support-Bibliothek 28.0.0 unterstützen Sie LabelVisibilityMode.

xml config: app: labelVisibilityMode = "beschriftet"

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

oder 

du kannst anrufen :

BottomNavigationView.setLabelVisibilityMode(LabelVisibilityMode.LABEL_VISIBILITY_LABELED);
1
qinmiao

Das funktioniert für mich:

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


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

Machen Sie diese Methode in Ihrer Aktivität oder Ihrem Fragment, an dem Sie anrufen möchten:

 @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

Ab der Unterstützungsbibliothek 28-alpha können wir app:labelVisibilityMode -Attribut für BottomNavigation-Komponente. Den Wert, den wir verwenden können, gibt es labeled, unlabeled, selected und auto.

  • labeled hält alle Beschriftungen sichtbar.
  • unlabeled zeigt nur Symbole an.
  • selected zeigt nur die Beschriftung für das ausgewählte Element und die Schichtelemente an.
  • auto wählt beschriftet oder ausgewählt aus, basierend auf der Anzahl der Artikel, die wir für 1–3 Artikel und für 3+ Artikel ausgewählt haben.

Dies ist ein Beispiel für die Verwendung:

<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"/>
0
Cevin Ways