导航抽屉:如何在启动时设置所选项目?

sin*_*rba 218 android navigation-drawer

我的代码完美无缺:每次点击导航抽屉中的项目时,都会选择该项目.

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

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;
[...]
Run Code Online (Sandbox Code Playgroud)

我想我需要在这里编辑:

if (menuItem.isChecked()) menuItem.setChecked(false);
                    else menuItem.setChecked(true);
Run Code Online (Sandbox Code Playgroud)

或者在onCreateApp启动时使用FragmentTransaction.

感谢您的支持.

Arl*_*ind 460

使用以下代码:

navigationView.getMenu().getItem(0).setChecked(true);
Run Code Online (Sandbox Code Playgroud)

打电话后调用此方法 setNavDrawer();

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

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

onNavigationItemSelected(navigationView.getMenu().getItem(0));
Run Code Online (Sandbox Code Playgroud)

以下是参考链接: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在下面回答.

  • Android支持库v23添加了[`setCheckedItem(int id)`](https://developer.android.com/reference/android/support/design/widget/NavigationView.html#setCheckedItem(int)). (62认同)
  • 由于某些原因,这两种方法都不适合我.但做`navigationView.post(new Runnable(){navigationView.setCheckedItem(...)})` - 工作. (3认同)
  • 不适合我!当为导航菜单抽屉中的其他选项调用方法[onNavigationItemSelected](https://developer.android.com/intl/pt-br/reference/android/support/design/widget/NavigationView.OnNavigationItemSelectedListener.html)时,被称为"已检查"的项目始终保持其状态.当我使用'navigationView.setCheckedItem(id);' 工作完美!之后,它必须调用方法'navigationView.getMenu()performIdentifierAction(R.id.nav_market,0);' 执行所需项目的选择. (2认同)

kin*_*ton 102

你也可以打电话:

navigationView.setCheckedItem(id);
Run Code Online (Sandbox Code Playgroud)

此方法在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>
Run Code Online (Sandbox Code Playgroud)

注意: android:checkableBehavior="single"

另请参见

  • @DeepeshDoshi请确保您有可检查的行为. (3认同)

Raj*_*har 47

对我来说这两种方法都不起作用:

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

尝试这个,它适合我.

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

  • 谢谢你的提示.上面的方法实际上没问题,但问题不同:如果使用它们,将不会调用onNavigationItemSelected,只会检查菜单项.所以我们需要调用这两种方法. (2认同)
  • onNavigationItemSelected(navView.getMenu()。getItem(0)); 或onNavigationItemSelected(navView.getMenu()。getItem(R.id.nav_profile)); 两者都对我有用,是getitem而不是finditem。 (2认同)

GFP*_*FPF 29

示例(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;
    }
Run Code Online (Sandbox Code Playgroud)

TKS

  • 这是一种方法,我喜欢它.但是,通常不鼓励使用仅代码的答案.我会编辑你的答案来解释一下代码,例如为什么你使用`performIdentifierAction`以及`onNavigationItemSelected`中发生了什么.对你而言,它似乎很简单,但是较新的开发者可能无法理解你的代码. (2认同)

Dan*_*l B 25

Googles总是存在问题"哦,太棒了"支持库.如果要在不降级支持库版本的情况下检查项目,只需在设置选中状态之前设置checkable.

MenuItem item = drawer.getMenu().findItem(R.id.action_something);
item.setCheckable(true);
item.setChecked(true);
Run Code Online (Sandbox Code Playgroud)

如果在菜单xml文件中设置了checkable,它也可能有效


Hug*_*ner 12

您可以使用以下1-liner突出显示并选择项目:

navigationView.getMenu().performIdentifierAction(R.id.posts, 0);
Run Code Online (Sandbox Code Playgroud)

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


Joh*_* P. 8

API 23提供以下方法:

navigationView.setCheckedItem(R.id.nav_item_id);
Run Code Online (Sandbox Code Playgroud)

但是,由于某种原因,此功能不会导致导航项后面的代码运行.该方法当然突出显示导航抽屉中的项目,或"检查"它,但OnNavigationItemSelectedListener如果您的启动屏幕取决于导航抽屉选择,它似乎不会在启动时调用结果为空白屏幕.可以手动调用监听器,但看起来很hacky:

if (savedInstanceState == null) this.onNavigationItemSelected(navigationView.getMenu().getItem(0));
Run Code Online (Sandbox Code Playgroud)

上面的代码假定:

  1. 您已NavigationView.OnNavigationItemSelectedListener在活动中实施
  2. 你已经打过:
    navigationView.setNavigationItemSelectedListener(this);
  3. 您要选择的项目位于0位置


MBH*_*MBH 6

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

第一:用于排除您在onNavigationItemSelected侦听器中实现的命令:

onNavigationItemSelected(navigationView.getMenu().getItem(R.id.nav_camera));
Run Code Online (Sandbox Code Playgroud)

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

navigationView.setCheckedItem(R.id.nav_camera);
Run Code Online (Sandbox Code Playgroud)

我打了两个函数,它对我有用.


小智 5

以下代码仅选择菜单项:

navigationView.setCheckedItem(id);

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

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


Par*_*sha 5

最简单的方法是从 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" />
Run Code Online (Sandbox Code Playgroud)

注意行 android:checked="true"