簡體   English   中英

Android - 底部導航菜單所選項目的圖標顏色不會因碎片而改變

[英]Android - Bottom Navigation menu selected item's icon color is not changing due to fragments

底部導航的選定項目的顏色沒有變化,盡管我提供了控制顏色變化的可繪制文件。 我已經嘗試過很多次,但我在代碼中找不到錯誤。

請幫忙!

這是底部導航

<com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="@color/bottomBackground"
        app:itemTextColor="@drawable/icon_color"
        app:itemIconTint="@drawable/icon_color"
        app:labelVisibilityMode="labeled"
        app:menu="@menu/bottom_navigation_menu"/>

這是 icon_color

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

編輯:

當我刪除這段代碼時它工作正常

        BottomNavigationView navigation = findViewById(R.id.navigation);
    navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
            int id = menuItem.getItemId();
            if(id == R.id.navigation_library) {
                loadFragment(new LibraryFragment());
            }
            else if (id == R.id.navigation_for_you) {
                loadFragment(new ForYouFragment());
            }
            return false;
        }
    });

為什么此代碼會干擾我的功能。

問題在這里:

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
       ...
       return false;  //Use true in your case
    }

您可以查看文檔:

退貨

boolean如果該項目不應該被選擇,則將項目顯示為已選項目,則為 true 考慮將不可選擇的項目預先設置為禁用,以使它們看起來非交互。

同樣在您的布局中使用:

<com.google.android.material.bottomnavigation.BottomNavigationView
        app:itemTextColor="@color/icon_color"

res/color文件夾中移動選擇器。

將代碼中的 false 替換為 true。 它會起作用的。

navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {

        //your code

        return true;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM