Почему BottomNavigationView не меняет значок выбранной вкладки? - PullRequest
0 голосов
/ 05 мая 2020

Я добавил BottomNavigationView. Когда я нажимаю на любую вкладку, заменяется только фрагмент, он не отображает значок и заголовок новой выбранной вкладки (вкладка «Главная» всегда отображается как выбранная). В чем проблема?

My XML макет - MainActivity. xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/FragmentContainerFrameLayout"
        android:layout_above="@id/bottomNavAppBar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/bottomNavAppBar"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.bottomnavigation.BottomNavigationView
            app:labelVisibilityMode="unlabeled"
            android:id="@+id/bottomNavgView"
            app:menu="@menu/bottom_nav"
            android:background="?android:attr/windowBackground"
            app:itemTextColor="#000"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </com.google.android.material.appbar.AppBarLayout>

</RelativeLayout>

Мой java код - MainActivity. java

public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {

    BottomNavigationView bottomNavigationView;
    Fragment selectedFragment;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bottomNavigationView=findViewById(R.id.bottomNavgView);
        bottomNavigationView.setOnNavigationItemSelectedListener(this);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId())
        {
            case R.id.homeMenu:
                selectedFragment=new HomeFragment();
                break;

            case R.id.searchMenu:
                selectedFragment=new SearchFragment();
                break;

            case R.id.addPostMenu:
                selectedFragment=null;
                startActivity(new Intent(MainActivity.this,AddPostActivity.class));
                break;

            case R.id.likesMenu:
                selectedFragment=new LikesFragment();
                break;

            case R.id.profileMenu:
                selectedFragment=new ProfileFragment();
                break;
        }

        if(selectedFragment!=null)
        {
            FragmentTransaction transaction=getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.FragmentContainerFrameLayout,selectedFragment);
            transaction.commit();
        }
        return false;
    }
}

Цвет файл - @ menu / bottom_nav

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@android:color/black" android:state_checked="true"/>
    <item android:color="@android:color/darker_gray"/>
</selector>

Файл Gradle

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

Файл меню

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item

        android:id="@+id/homeMenu"
        android:title="Home"
        android:icon="@drawable/ic_home"></item>

    <item
        android:id="@+id/searchMenu"
        android:title="Search"
        android:icon="@drawable/ic_search"></item>


    <item
        android:id="@+id/addPostMenu"
        android:title="Add Post"
        android:icon="@drawable/ic_add_post"></item>


    <item
        android:id="@+id/likesMenu"
        android:title="Likes"
        android:icon="@drawable/ic_like"></item>

    <item
        android:id="@+id/profileMenu"
        android:title="Profile"
        android:icon="@drawable/ic_profile"></item>

</menu>

Я не совершал ничего необычного. Почему это происходит? Пожалуйста, помогите мне.

  • Значок первого пункта меню всегда выбран, не меняется

  • Правильный фрагмент заменяется, но не отображается значок и заголовок.

1 Ответ

1 голос
/ 05 мая 2020

Вы должны вернуть true в методе onNavigationItemSelected:

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
       ...
       return true;  
    }

Вы можете проверить do c:

Возвращает

boolean true, чтобы отобразить элемент как выбранный элемент, и false, если элемент не должен быть выбран . Подумайте о том, чтобы установить невыбираемые элементы как отключенные заранее, чтобы они не отображались в интерактивном режиме.

Также вы используете app:labelVisibilityMode="unlabeled".
Это означает, что метка скрыта для всех элементов навигации (LABEL_VISIBILITY_UNLABELED)

...