35

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) 
4

14 回答 14

57

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.

于 2017-04-06T05:04:45.483 回答
23

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;
    }
}
于 2017-04-06T05:28:34.250 回答
9

Kotlin Solution

In a Fragment

getActivity()?.myNavigationViewId?.selectedItemId = R.id.other_tab_id

In an Activity

myNavigationViewId?.selectedItemId = R.id.other_tab_id

NOTE: Make sure to replace myNavigationViewId and other_tab_id with your actual navigation view and tab ids.

于 2020-05-24T21:46:32.713 回答
6

FYI: for fragment, onCreateView

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

mBottomNavigationView.setSelectedItemId(R.id.your_item);
于 2019-07-17T20:47:36.893 回答
4

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.

于 2018-03-19T11:41:06.037 回答
4

Kotlin solution with Fragment

var fragment = Fragment()
bottomNav = findViewById(R.id.bottom_nav)
bottomNav.setOnNavigationItemSelectedListener { item ->
  when (item.itemId) {
    R.id.home -> {
      fragment = HomeForm()
    }
    R.id.score -> {
      fragment = ScoreForm()
    }
  }
  supportFragmentManager
    .beginTransaction()
    .replace(R.id.frame_layout, fragment)
    .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
    .commit()
  true
}
bottomNav.selectedItemId = R.id.score // init open score tab
于 2020-08-02T11:16:50.573 回答
2

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);
    }
于 2018-03-19T12:36:56.533 回答
2

You can use:

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

and it will not fire OnNavigationItemSelectedListener events.

于 2019-01-29T14:49:05.517 回答
1

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!
}
于 2018-03-02T12:14:52.917 回答
1

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.

于 2018-06-23T17:31:20.007 回答
0

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
}
于 2018-08-15T13:35:44.857 回答
0

There are two senario

Set the selected menu item ID. This behaves the same as tapping on an item.

Code example:

BottomNavigationView bottomNavigationView;
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(myNavigationItemListener);
bottomNavigationView.setSelectedItemId(R.id.my_menu_item_id);

I you only need to check it without tapping

Code example:

  BottomNavigationView bottomNavigationView= (getActivity()).findViewById(R.id.bottom_navigation);
    bottomNavigationView.getMenu().findItem(R.id.action_manage_orders_id).setChecked(true);
于 2020-02-06T08:05:07.163 回答
0

For me, setSelectedItemId(int id) only showed the fragment, but selected menu item was still the wrong one.

I figured out that calling setSelectedItemId(int id) after the BottomNavigationView is all set up is not enough.

I stopped calling setSelectedItemId(int id) in onCreate(savedInstanceState: Bundle?) and started calling it in onResume() instead. That fixed the problem.

于 2021-06-04T14:41:18.437 回答
0

I should be like below in case if you are using with navigation component and want all control.

  private fun setupDashboard() {
    binding.navBottomHome.setOnNavigationItemSelectedListener {
        when (it.itemId) {
            R.id.dashboardFragment -> {
                findNavController(viewId = R.id.dashboardNavGraph).navigate(R.id.dashboardFragment)
                binding.navBottomHome.isSelected = true
            }
            R.id.ordersFragment -> {
                findNavController(viewId = R.id.dashboardNavGraph).navigate(R.id.ordersFragment)
                binding.navBottomHome.isSelected = true
            }
            R.id.productsFragment -> {
                findNavController(viewId = R.id.dashboardNavGraph).navigate(R.id.productsFragment)
                binding.navBottomHome.isSelected = true
            }
            else -> {
                findNavController(viewId = R.id.dashboardNavGraph).navigate(R.id.settingsFragment)
                binding.navBottomHome.isSelected = true
            }
        }
        Log.d("TAG++", "Item selected")
        true
    }
}

in short setting the listener and setting binding.navBottomHome.isSelected = true works.

于 2021-11-20T07:19:07.727 回答