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

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

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 .setChecked .getItem (0) () (true); navigationView.setCheckedItem (id);

试试这个,对我很管用。

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

其他回答

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

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

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

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

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

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

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

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

试试这个,对我很管用。

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

你也可以拨打:

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 = "单"

看这个