38

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) 
Abhijeet
  • 481
  • 1
  • 6
  • 14

14 Answers14

62

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.

Abhishek Singh
  • 9,008
  • 5
  • 28
  • 53
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;
    }
}
Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212
Magesh Pandian
  • 8,789
  • 12
  • 45
  • 60
12

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.

Gibolt
  • 42,564
  • 15
  • 187
  • 127
9

FYI: for fragment, onCreateView

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

mBottomNavigationView.setSelectedItemId(R.id.your_item);
Ego Slayer
  • 1,987
  • 2
  • 22
  • 17
  • 2
    thank you for this! I kept getting a NPE. I needed your `getActivity()` in order to execute the `findViewById(R.id.bottom_nav)` because I was doing it from a fragment. Thank you. – Forrest Mar 10 '20 at 13:39
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.

Jemshit
  • 9,501
  • 5
  • 69
  • 106
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
Infomaster
  • 793
  • 7
  • 8
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);
    }
SANAT
  • 8,489
  • 55
  • 66
2

You can use:

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

and it will not fire OnNavigationItemSelectedListener events.

Daniel Gomez Rico
  • 15,026
  • 20
  • 92
  • 162
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!
}
Konstantin Konopko
  • 5,229
  • 4
  • 36
  • 62
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.

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);
Mohamed AbdelraZek
  • 2,503
  • 4
  • 25
  • 36
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.

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.

vikas kumar
  • 10,447
  • 2
  • 46
  • 52
-1

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
}
Rodolfo Abarca
  • 565
  • 7
  • 15