BottomNavigationView会持续检查上一个菜单项(启动时),但会显示第一个菜单项

时间:2017-08-02 04:56:26

标签: android bottomnavigationview

当应用程序首次启动时,它会检查最后一个菜单项,就像它被点击一样。它显示第一个menuitem内容。在Android Studio中,不会显示任何错误,警告或日志,提示出现任何错误。

应用程序运行后,如果我点击任何其他菜单项,它就能正常运行。我可以点击每个菜单项,相应地填充正确的片段。

以下是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);
        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);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt(SELECTED_ITEM, mSelectedItem);
        super.onSaveInstanceState(outState);
    }

    @Override
    /* This is never called on start up */
    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.menu_home:
                frag = HomeFragment.newInstance();
                break;
            case R.id.menu_archives:
                frag = ArchivesFragment.newInstance();
                break;
            case R.id.menu_inspirational:
                frag = InspirationalFragment.newInstance();
                break;
            case R.id.menu_search:
                frag = SearchFragment.newInstance();
                break;
        }

        // update selected item
        mSelectedItem = item.getItemId();

        // unchecked the other items.
        //THIS LINE HERE
        for (int i = 0; i < mBottomNav.getMenu().size(); i++) {
            MenuItem menuItem = mBottomNav.getMenu().getItem(i);
            menuItem.setChecked(menuItem.getItemId() == mSelectedItem);
        }

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

以下是activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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.ourdailystrength.mobile.android.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>

以下是bottom_nav_items.xml

<?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/menu_home"
        android:title="@string/menu_home"
        android:icon="@drawable/ic_home_black_48dp"
        android:checked="true" <!-- Doesn't matter if this line is included or not -->
        app:showAsAction="ifRoom"/>

    <item
        android:id="@+id/menu_archives"
        android:title="@string/menu_archives"
        android:icon="@drawable/ic_archive_black_48dp"
        app:showAsAction="ifRoom"/>

    <item
        android:id="@+id/menu_search"
        android:title="@string/menu_search"
        android:icon="@drawable/ic_search_black_48dp"
        app:showAsAction="ifRoom"/>

    <item
        android:id="@+id/menu_inspirational"
        android:title="@string/menu_inspirational"
        android:icon="@drawable/ic_photo_black_48dp"
        app:showAsAction="ifRoom"/>
</menu>

以下是首次启动时的屏幕截图:

enter image description here

为什么要检查最后一个菜单项而不是第一个菜单项?

修改: 所以,根据下面给出的答案,我做了这个改变并且它有效:

private void selectFragment(MenuItem item) {
    Fragment frag = null;

    // update selected item
    mSelectedItem = item.getItemId();

    // unchecked the other items.
    for (int i = 0; i < mBottomNav.getMenu().size(); i++) {
        MenuItem menuItem = mBottomNav.getMenu().getItem(i);
        menuItem.setChecked(false);
    }

    // init corresponding fragment
    switch (mSelectedItem) {
        case R.id.menu_home:
            frag = HomeFragment.newInstance();
            mBottomNav.getMenu().findItem(R.id.menu_home).setChecked(true);
            break;
        case R.id.menu_archives:
            frag = ArchivesFragment.newInstance();
            mBottomNav.getMenu().findItem(R.id.menu_archives).setChecked(true);
            break;
        case R.id.menu_inspirational:
            frag = InspirationalFragment.newInstance();
            mBottomNav.getMenu().findItem(R.id.menu_inspirational).setChecked(true);
            break;
        case R.id.menu_search:
            frag = SearchFragment.newInstance();
            mBottomNav.getMenu().findItem(R.id.menu_search).setChecked(true);
            break;
    }

    updateToolbarText(item.getTitle());

    if (frag != null) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.container, frag, frag.getTag());
        ft.commit();
    }
}

为什么上面代码中的THIS LINE HERE会导致它出现这种奇怪的错误?

3 个答案:

答案 0 :(得分:0)

希望这可以帮助您解决问题。 每当您更改Fragment时,请调用此方法。根据您的需要通过checkedcolorunchecked color

 private void changeMenuItemCheckedStateColor(int checkedColor, int uncheckedColor) {
        int[][] states = new int[][]{
                new int[]{-android.R.attr.state_checked}, // unchecked
                new int[]{android.R.attr.state_checked}, // checked
        };
        int[] colors = new int[]{
                uncheckedColor,
                checkedColor
        };
        ColorStateList colorStateList = new ColorStateList(states, colors);
        bottomNavigationView.setItemTextColor(colorStateList);
        bottomNavigationView.setItemIconTintList(colorStateList);
    }

答案 1 :(得分:0)

有2个解决方案

1)使用群组

<group android:checkableBehavior="single">
   <item .../>
   <item .../>
   <item .../>
</group>

2)通过编程方式进行

Menu bottomMenu;
BottomNavigationView bottomNavigationMenu = (BottomNavigationView) findViewById(R.id.bottom_navigation);
bottomMenu = navigation.getMenu();
bottomMenu.findItem(R.id.menu_home).setChecked(true);

希望它会有所帮助,如果您有任何疑问,请发表评论。

答案 2 :(得分:0)

删除以下代码:

// unchecked the other items.
        for (int i = 0; i < mBottomNav.getMenu().size(); i++) {
            MenuItem menuItem = mBottomNav.getMenu().getItem(i);
            menuItem.setChecked(menuItem.getItemId() == mSelectedItem);
        }

并在BottomNavigationView:

中给出色调颜色
<android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="start"
        app:itemIconTint="@drawable/nav_item_color_state"
        design:menu="@menu/bottom_nav_items" />