我的代码工作得很完美:每次单击导航抽屉中的项目时,项目就会被选中。

当然,我想启动应用程序与默认片段(家),但导航抽屉没有选择的项目。如何以编程方式选择该项目?

public class BaseApp extends AppCompatActivity {

    //Defining Variables
    protected String LOGTAG = "LOGDEBUG";
    protected Toolbar toolbar;
    protected NavigationView navigationView;
    protected DrawerLayout drawerLayout;

    private DateManager db = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.base_layout);

        navigationView = (NavigationView) findViewById(R.id.navigation_view);


        // set the home/dashboard at startup

        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.frame, new DashboardFragment());
        fragmentTransaction.commit();

        setNavDrawer();
    }

    private void setNavDrawer(){

        // Initializing Toolbar and setting it as the actionbar
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //Initializing NavigationView

        //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

            // This method will trigger on item Click of navigation menu
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {


                //Checking if the item is in checked state or not, if not make it in checked state

                // I THINK THAT I NEED EDIT HERE...

                if (menuItem.isChecked()) menuItem.setChecked(false);
                else menuItem.setChecked(true);

                //Closing drawer on item click
                drawerLayout.closeDrawers();


                //Check to see which item was being clicked and perform appropriate action
                switch (menuItem.getItemId()) {    

                    //Replacing the main content with ContentFragment 

                    case R.id.home:

                        DashboardFragment dashboardFragment = new DashboardFragment();
                        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                        fragmentTransaction.replace(R.id.frame, dashboardFragment,"DASHBOARD_FRAGMENT");
                        fragmentTransaction.commit();
                        return true;
[...]

我认为我需要在这里进行编辑:

if (menuItem.isChecked()) menuItem.setChecked(false);
                    else menuItem.setChecked(true);

或者在onCreate中在App启动时使用FragmentTransaction。

谢谢你的支持。


使用下面的代码:

navigationView.getMenu().getItem(0).setChecked(true);

在调用setNavDrawer()之后调用此方法;

getItem(int index)方法获取MenuItem,然后你可以调用setChecked(true);在这个MenuItem上,剩下要做的就是找出默认的元素索引,并用该索引替换0。

您可以通过调用来选择(突出显示)项目

onNavigationItemSelected(navigationView.getMenu().getItem(0));

这里有一个参考链接:http://thegeekyland.blogspot.com/2015/11/navigation-drawer-how-set-selected-item.html

编辑 在nexus 4上无法使用,支持库版本24.0.0。我推荐使用

navigationView.setCheckedItem(R.id.nav_item);

下面是@kingston的回复。


你也可以拨打:

navigationView.setCheckedItem(id);

此方法在API 23.0.0中引入

例子

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      tools:ignore="UnusedIds">

    <group
        android:id="@+id/group"
        android:checkableBehavior="single">
        <item
            android:id="@+id/menu_nav_home"
            android:icon="@drawable/ic_home_black_24dp"
            android:title="@string/menu_nav_home" />
    </group>
</menu>

注意:android: checkableBehavior = "单"

看这个


首先,为选定的项目创建颜色。这里https://stackoverflow.com/a/30594875/1462969很好的例子。它可以帮助你改变图标的颜色。为了改变所有选定项目的背景添加到您的价值\style.xml文件this

  <item name="selectableItemBackground">@drawable/selectable_item_background</item>

在drawable/selectable_item_background.xml中应该声明selectable_item_background

  <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/accent_translucent"
      android:state_pressed="true" />
    <item android:drawable="@android:color/transparent" />
   </selector>

哪里可以在style.xml中声明颜色

 <color name="accent_translucent">#80FFEB3B</color>

在这之后

   // The main navigation menu with user-specific actions
        mainNavigationMenu_ = (NavigationView) findViewById(R.id.main_drawer);
        mainNavigationMenu_.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                mainNavigationMenu_.getMenu().findItem(itemId).setChecked(true);
                return true;
            }
        });

正如你看到的,我用了这个 .setChecked mainNavigationMenu_.getMenu () .findItem (itemId)(真正的); 设置所选项目。 这里navigationView

 <android.support.design.widget.NavigationView
        android:id="@+id/main_drawer"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/header_main_navigation_menu"
        app:itemIconTint="@color/state_list"
        app:itemTextColor="@color/primary"
        app:menu="@menu/main_menu_drawer"/>

对我来说,这两种方法都不奏效:

navigationView.getMenu .setChecked .getItem (0) () (true); navigationView.setCheckedItem (id);

试试这个,对我很管用。

onNavigationItemSelected (navigationView.getMenu () .findItem (R.id.nav_profile));


出于某种原因,最好使用ID来查找MenuItem。

drawer.getMenu().findItem(R.id.action_something).setChecked(true);

例子(NavigationView.OnNavigationItemSelectedListener):

private void setFirstItemNavigationView() {
        navigationView.setCheckedItem(R.id.custom_id);
        navigationView.getMenu().performIdentifierAction(R.id.custom_id, 0);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setFirstItemNavigationView();
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    FragmentManager fragmentManager = getFragmentManager();

    switch (item.getItemId()) {
        case R.id.custom_id:
            Fragment frag = new CustomFragment();

            // update the main content by replacing fragments
            fragmentManager.beginTransaction()
                    .replace(R.id.viewholder_container, frag)
                    .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                    .addToBackStack(null)
                    .commit();
            break;
    }

Tks


谷歌的“哦,太棒了”支持库总是有问题。如果你想检查一个项目而不降低你的支持库版本,只需要在设置检查状态之前设置checkable。

MenuItem item = drawer.getMenu().findItem(R.id.action_something);
item.setCheckable(true);
item.setChecked(true);

如果你在菜单xml文件中设置checkable,它也可以工作


以下代码将只使菜单项被选中:

navigationView.setCheckedItem (id);

要选择并打开菜单项,请在上面的行后添加以下代码。

onNavigationItemSelected (navigationView.getMenu () .getItem (0));


您可以用下面的一行代码突出显示和选择项目:

navigationView.getMenu().performIdentifierAction(R.id.posts, 0);

来源:https://stackoverflow.com/a/31044917/383761


API 23提供了以下方法:

navigationView.setCheckedItem(R.id.nav_item_id);

但是,由于某种原因,这个函数没有导致导航项后面的代码运行。该方法当然会突出显示导航抽屉中的项目,或“检查”它,但它似乎不会调用OnNavigationItemSelectedListener,导致启动时出现空白屏幕,如果您的启动屏幕依赖于导航抽屉的选择。可以手动调用监听器,但看起来很俗气:

if (savedInstanceState == null) this.onNavigationItemSelected(navigationView.getMenu().getItem(0));

上面的代码假设:

你已经实现了 NavigationView。OnNavigationItemSelectedListener在你的活动 您已经呼叫过: navigationView.setNavigationItemSelectedListener(这个); 您要选择的项目位于位置0


这就是我的解,很简单。

这是我的menu.xml文件:

<group
    android:id="@+id/grp1"
    android:checkableBehavior="single">
    <item
        android:id="@+id/nav_all_deals"
        android:checked="true"
        android:icon="@drawable/ic_all_deals"
        android:title="@string/all_deals" />
    <item
        android:id="@+id/nav_news_and_events"
        android:icon="@drawable/ic_news"
        android:title="@string/news_and_events" />
    <item
        android:id="@+id/nav_histories"
        android:icon="@drawable/ic_histories"
        android:title="@string/histories" />
</group>

上面的菜单将突出显示第一个菜单项。下面一行将做一些事情(例如:显示第一个片段等)。注意:写在“configure your drawer code”后面

onNavigationItemSelected(mNavigationView.getMenu().getItem(0));

你必须为此调用2个函数:

首先:执行你在onNavigationItemSelected监听器中实现的命令:

onNavigationItemSelected(navigationView.getMenu().getItem(R.id.nav_camera));

第二:将导航抽屉菜单项的状态更改为选中(或选中):

navigationView.setCheckedItem(R.id.nav_camera);

我调用了两个函数,它对我有效。


下面的代码用于选择第一个项目并在菜单中突出显示所选的第一个项目。

onNavigationItemSelected(mNavigationView.getMenu().getItem(0).setChecked(true));

为导航抽屉的个别项目做一个选择器

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/darkBlue" android:state_pressed="true"/>
    <item android:drawable="@color/darkBlue" android:state_checked="true"/>
    <item android:drawable="@color/textBlue" />
</selector>

在你的NavigationView中做一些改变

<android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:itemBackground="@drawable/drawer_item"
        android:background="@color/textBlue"
        app:itemIconTint="@color/white"
        app:itemTextColor="@color/white"
        app:menu="@menu/activity_main_drawer"
        />

最简单的方法是从xml中选择它,如下所示:

<menu>
   <group android:checkableBehavior="single">
         <item
              android:checked="true"
              android:id="@+id/nav_home"
              android:icon="@drawable/nav_home"
              android:title="@string/main_screen_title_home" />

注意这一行android:checked="true"


关于你的活动(在抽屉后面):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar,
               R.string.navigation_drawer_open,
               R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    navigationView.setCheckedItem(R.id.nav_portfolio);
    onNavigationItemSelected(navigationView.getMenu().getItem(0));
}

and

@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    Fragment fragment = null;

    if (id == R.id.nav_test1) {
        fragment = new Test1Fragment();
        displaySelectedFragment(fragment);
    } else if (id == R.id.nav_test2) {
        fragment = new Test2Fragment();
        displaySelectedFragment(fragment);
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

在菜单中:

<group android:checkableBehavior="single">

    <item
        android:id="@+id/nav_test1"
        android:title="@string/test1" />

    <item
        android:id="@+id/nav_test2"
        android:title="@string/test2" />

  </group>

第一个菜单被高亮显示为默认菜单。


当使用BottomNavigationView时,其他答案如navigationView.getMenu().getItem(0).setChecked(true);和 navigationView.setCheckedItem (id);不会工作调用setSelectedItemId工作:

    BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation_view);

    bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
            // TODO: 10-Aug-19 your code here 
        }
    });

    bottomNavigationView.setSelectedItemId(R.id.myitem);

你可以这样做, nav_view.getMenu () .findItem (R.id.menutem) .setChecked(真正的)


bottomNavigationView.setSelectedItemId(R.id.menuItem);

上面为我工作,但我已经把它放在onResume()方法。放置在 onNavigationItemSelected(@NonNull MenuItem项)导致我在活动之间来回切换时出现问题

   private BottomNavigationView bottomNavigationView;
    
     @Override
        public void onResume(){
            super.onResume();
            bottomNavigationView.setSelectedItemId(R.id.menuItem);
    
     } 

    package com.example.projectdesign;
    import androidx.annotation.NonNull;
    import androidx.appcompat.app.ActionBarDrawerToggle;
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.core.view.GravityCompat;
    import androidx.drawerlayout.widget.DrawerLayout;
    import androidx.fragment.app.Fragment;
         import android.annotation.SuppressLint;
      import android.app.Activity;
     import android.content.Intent;
     import android.os.Bundle;
     import android.view.MenuItem;
    import android.widget.Toast;

    import com.google.android.material.navigation.NavigationView;

    public class MenuDrawer extends AppCompatActivity implements 
    NavigationView.OnNavigationItemSelectedListener{
    public DrawerLayout drawerLayout;
    public ActionBarDrawerToggle actionBarDrawerToggle;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu_drawer);

        drawerLayout = findViewById(R.id.my_drwaer_layout);
        actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, 
      R.string.nav_open, R.string.nav_close);
        drawerLayout.addDrawerListener(actionBarDrawerToggle);
        actionBarDrawerToggle.syncState();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        NavigationView navigationView = findViewById(R.id. nav_view ) ;
        navigationView.setNavigationItemSelectedListener( this ) ;
    }
    @SuppressLint("ResourceType")
    @SuppressWarnings ( "StatementWithEmptyBody" )
     @Override
    public boolean onNavigationItemSelected (MenuItem item){
        int id=item.getItemId();
        switch (id){
            case R.id.nav_account:
                Intent intent= new Intent(MenuDrawer.this, UsingBackKey.class);
                startActivity(intent);
                break;
            case R.id.women:
     
     
    getSupportFragmentManager().beginTransaction().replace(R.id.my_drwaer_layout,new 
    Fragment2()).commit();
                break;
            case R.id.men:
                Toast.makeText(getApplicationContext(),"Soon", 
   Toast.LENGTH_SHORT).show();
                break;
            case R.id.kids:
              Toast.makeText(getApplicationContext(),"Welcome to Kids", 
      Toast.LENGTH_SHORT).show();
                break;
        }
        drawerLayout.closeDrawer(GravityCompat.START);
        return super.onContextItemSelected(item);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {


        if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        return super.onOptionsItemSelected(item);

    }

    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
        super.onBackPressed();
    }
}