如何在BottomNavigationView中设置所选项目

问题描述 投票:13回答:8

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

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) 
android bottomnavigationview
8个回答
10
投票

只需分享我的工作源代码

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

24
投票

而不是选择你需要setChecked(true)该项目。试试这个代码

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

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


2
投票

Kotlin扩展版Abshishek's回答:

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

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

这不会触发OnNavigationItemSelectedListener


2
投票

您可以使用:

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

它不会引发OnNavigationItemSelectedListener事件。


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

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

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


0
投票

如果你想要的是在视图上忽略被点击的元素而不是作为“选中”返回,你可以在处理点击后返回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
}

0
投票

仅供参考:对于片段,onCreateView

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

mBottomNavigationView.setSelectedItemId(R.id.your_item);
© www.soinside.com 2019 - 2024. All rights reserved.