How to Set selected item in BottomNavigationView

人走茶凉 提交于 2019-12-03 19:21:01

问题


I am trying to set default item on activity created but it isn't working? This is my code:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_userhome);
    mTextMessage = (TextView) findViewById(R.id.message);
    profile = (FrameLayout) findViewById(R.id.profile);
    mall = (FrameLayout) findViewById(R.id.mall);
    dietplan =(FrameLayout) findViewById(R.id.dietplan);
    BottomNavigationView navigation = (BottomNavigationView) 
    findViewById(R.id.navigation);
    navigation.setSelectedItemId(R.id.dietplan);
     navigation.setOnNavigationItemSelectedListener 
    (mOnNavigationItemSelectedListener);
}

But it seems that navigation.setSelectedItemId(R.id.dietplan); is not working. Please help me to set default item of bottom navigation bar:

This is my stack trace(logcat):

FATAL EXCEPTION: main
   Process: gym.android.ommsoftware.gym, PID: 1915
   java.lang.RuntimeException: Unable to start activity ComponentInfo{gym.android.ommsoftware.gym/gym.android.ommsoftware.gym.Userhome}: java.lang.NullPointerException
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2404)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2464)
       at android.app.ActivityThread.access$900(ActivityThread.java:172)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:146)
       at android.app.ActivityThread.main(ActivityThread.java:5653)
       at java.lang.reflect.Method.invokeNative(Native Method)
       at java.lang.reflect.Method.invoke(Method.java:515)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
       at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.NullPointerException
       at gym.android.ommsoftware.gym.Userhome.onCreate(Userhome.java:57)
       at android.app.Activity.performCreate(Activity.java:5541)
       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2368)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2464) 
       at android.app.ActivityThread.access$900(ActivityThread.java:172) 
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308) 
       at android.os.Handler.dispatchMessage(Handler.java:102) 
       at android.os.Looper.loop(Looper.java:146) 
       at android.app.ActivityThread.main(ActivityThread.java:5653) 
       at java.lang.reflect.Method.invokeNative(Native Method) 
       at java.lang.reflect.Method.invoke(Method.java:515) 
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291) 
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107) 
       at dalvik.system.NativeStart.main(Native Method) 

回答1:


Just share my working source code

In Xml,

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.design.widget.BottomNavigationView
        android:background="@color/colorWhite"
        android:id="@+id/gfPrlBnvBtmView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="start"
        android:layout_alignParentBottom="true"
        app:menu="@menu/bottom_navigation_main" />
</LinearLayout>

In Java,

  public class TestActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener
{
    private BottomNavigationView mBtmView;
    private int mMenuId;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        setContentView(R.layout.test);
        mBtmView = (BottomNavigationView) findViewById(R.id.gfPrlBnvBtmView);
        mBtmView.setOnNavigationItemSelectedListener(this);
        mBtmView.getMenu().findItem(R.id.action_yoga).setChecked(true);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        // uncheck the other items.
        mMenuId = item.getItemId();
        for (int i = 0; i < mBtmView.getMenu().size(); i++) {
            MenuItem menuItem = mBtmView.getMenu().getItem(i);
            boolean isChecked = menuItem.getItemId() == item.getItemId();
            menuItem.setChecked(isChecked);
        }

        switch (item.getItemId()) {
            case R.id.action_food: {
            }
            break;
            case R.id.action_medical: {
            }
            break;
            case R.id.action_yoga: {
            }
            break;
            case R.id.action_postures: {
            }
            break;
        }
        return true;
    }
}



回答2:


Instead of selected you need to setChecked(true) that item. Try this code

mBottomNavigationView=(BottomNavigationView)findViewById(R.id.bottom_nav);
mBottomNavigationView.getMenu().findItem(R.id.item_id).setChecked(true);

Checked item is highlighted in BottomNavigationView.




回答3:


Kotlin extension version of Abshishek's answer:

internal fun BottomNavigationView.checkItem(actionId: Int) {
    menu.findItem(actionId)?.isChecked = true
}

// use 
bottom_navigation.checkItem(R.id.navigation_home)

This does not trigger OnNavigationItemSelectedListener.




回答4:


You can use:

    navigationView?.menu?.findItem(drawableMenuItem.id)?.isChecked = true

and it will not fire OnNavigationItemSelectedListener events.




回答5:


This works for me

Activity layout:

<android.support.design.widget.BottomNavigationView
        android:id="@+id/bottomNavigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:itemBackground="@color/colorPrimary"
        app:itemIconTint="@color/tabs"
        app:itemTextColor="@color/tabs"
        app:menu="@menu/bottom_navigation_main" />

color/tabs.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:color="@color/not_active" android:state_checked="false"/>
    <item android:color="@color/active" android:state_checked="true"/>

</selector>

Click callback:

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_tab0:
            setFragment(f0);
            break;
        case R.id.action_tab1:
            setFragment(f1);
            break;
    }
    return true; // not false!
}



回答6:


You can also set selection in BottomNavigatioView using index like this :

public void selectBottomNavigationOption(int index) {
        switch (index) {
            case 0:
                index = R.id.action_1;
                break;
            case 1:
                index = R.id.action_2;
                break;
            case 2:
                index = R.id.action_3;
                break;
            case 3:
                index = R.id.action_4;
                break;
        }
        bottomNavigationView.setSelectedItemId(index);
    }



回答7:


Add android:enabled="true" to your BottomNavigation menu items.

<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <item
    android:id="@+id/menu_id"
    android:enabled="true"
    android:icon="@drawable/ic_my_icon"
    android:title="@string/menu_title"/>
</menu>

And in onCreate() method, set up listeners by bottomNavigationView.setOnNavigationItemSelectedListener(mListener).

And set the desired item to be selected by doing bottomNavigationView.selectedItemId = R.id.menu_id.

This will trigger onNavigationItemSelected() from the NavigationItemSelectedListener whenever the activity is created.




回答8:


If what you want is that the clicked element is ignored on the view and is not returned as "selected" you can return false after the click is handled, in some cases and some designs you could need to open an activity instead of a fragment and this will make selected the bottom item after the activity is closed.

private val onNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
    when (item.itemId) {
        R.id.navigation_shipment -> {
            currentItem = TAB_INDEX_SHIPMENT
            val intent = Intent(this, BookShipmentActivity::class.java)
            startActivity(intent)
            return@OnNavigationItemSelectedListener false
        }
    }
    false
}



回答9:


FYI: for fragment, onCreateView

BottomNavigationView mBottomNavigationView = getActivity().findViewById(R.id.bottomNavigationView);

mBottomNavigationView.setSelectedItemId(R.id.your_item);


来源:https://stackoverflow.com/questions/43246059/how-to-set-selected-item-in-bottomnavigationview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!