如何在BottomNavigationView中设置所选项目

时间:2017-04-06 05:00:36

标签: android bottomnavigationview

我正在尝试在创建的活动上设置默认项目,但它不起作用? 这是我的代码:

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

但似乎navigation.setSelectedItemId(R.id.dietplan);无效。请帮我设置底部导航栏的默认项目:

这是我的堆栈跟踪(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) 

13 个答案:

答案 0 :(得分:23)

您需要setChecked(true)该项目,而非选择。试试这段代码

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

选中的项目在BottomNavigationView中突出显示。

答案 1 :(得分:9)

只需分享我的工作源代码

在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>

在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 :(得分:6)

科特林溶液

在片段中

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

在活动中

myNavigationViewId?.selectedItemId = R.id.other_tab_id

注意:请确保将myNavigationViewIdother_tab_id替换为实际的导航视图和标签ID。

答案 3 :(得分:2)

Kotlin片段溶液

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

答案 4 :(得分:1)

这对我有用

活动布局:

<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" />

<强>颜色/ 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>

点击回调:

@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!
}

答案 5 :(得分:1)

您还可以使用以下索引在BottomNavigatioView中设置选择:

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

答案 6 :(得分:1)

android:enabled="true" 添加到您的BottomNavigation菜单项。

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

onCreate()方法中, 通过设置听众  bottomNavigationView.setOnNavigationItemSelectedListener(mListener)

并通过执行bottomNavigationView.selectedItemId = R.id.menu_id设置要选择的所需项目。

无论何时创建活动,这都会从onNavigationItemSelected()触发NavigationItemSelectedListener

答案 7 :(得分:1)

您可以使用:

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

,它将不会触发OnNavigationItemSelectedListener个事件。

答案 8 :(得分:0)

Kotlin扩展版Abshishek's回答:

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

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

这不会触发OnNavigationItemSelectedListener

答案 9 :(得分:0)

如果您想要的是在视图上忽略clicked元素,并且不将其作为“ selected”返回,则可以在处理了click之后返回false,在某些情况下和某些设计中,您可能需要打开活动而不是一个片段,活动结束后,这将使所选内容成为底部的项目。

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
}

答案 10 :(得分:0)

仅供参考:对于片段,onCreateView

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

mBottomNavigationView.setSelectedItemId(R.id.your_item);

答案 11 :(得分:0)

有两个senario

设置所选菜单项的ID。行为与点击项目相同。

代码示例:

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

我只需要检查它而无需点击

代码示例:

  BottomNavigationView bottomNavigationView= (getActivity()).findViewById(R.id.bottom_navigation);
    bottomNavigationView.getMenu().findItem(R.id.action_manage_orders_id).setChecked(true);

答案 12 :(得分:0)

对我来说,setSelectedItemId(int id) 只显示了片段,但选择的菜单项仍然是错误的。

我发现在 setSelectedItemId(int id) 全部设置后调用 BottomNavigationView 是不够的。

我不再在 setSelectedItemId(int id) 中调用 onCreate(savedInstanceState: Bundle?),而是开始在 onResume() 中调用它。这解决了问题。