简体   繁体   English

导航抽屉项目单击侦听器不起作用

[英]Navigation drawer item click listener not working

Sorry for the silly question i am amateur in android studio and learning now.抱歉这个愚蠢的问题,我是 android 工作室的业余爱好者,现在正在学习。 I have tried a lot but the click listener is not working please help.我已经尝试了很多,但点击监听器不起作用,请帮忙。 i have used the android studio's default drawer layout.navigation is working but i want to perform a special action such as using a new intent to open another app.I am trying to use it on the ID nav_link to perform a simple toast but its not working.我使用了 android 工作室的默认抽屉布局。导航正在工作,但我想执行特殊操作,例如使用新意图打开另一个应用程序。我试图在ID nav_link上使用它来执行简单的 toast,但它不是在职的。

package com.demo.navdraw;
import android.content.ClipData;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import android.widget.Toast;



import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

private AppBarConfiguration mAppBarConfiguration;
private MenuItem item;

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.activity_main_drawer, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();


    if (id == R.id.nav_link) {
        Toast.makeText(this, "Setting", Toast.LENGTH_LONG).show();
        return true;
    }

    return super.onOptionsItemSelected(item);
}


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



    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });



    DrawerLayout drawer=findViewById(R.id.drawer_layout);
    NavigationView navigationView=findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    mAppBarConfiguration=new AppBarConfiguration.Builder(
            R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
            R.id.nav_tools, R.id.nav_share, R.id.nav_send, R.id.nav_profile, R.id.nav_link)
            .setDrawerLayout(drawer)
            .build();
    NavController navController=Navigation.findNavController(this, R.id.nav_host_fragment);
    NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
    NavigationUI.setupWithNavController(navigationView, navController);


}

@Override
public boolean onSupportNavigateUp() {
    NavController navController=Navigation.findNavController(this, R.id.nav_host_fragment);
    return NavigationUI.navigateUp(navController, mAppBarConfiguration)
            || super.onSupportNavigateUp();
}


@Override
public boolean onNavigationItemSelected(@NonNull MenuItem Item) {
    int id=item.getItemId();

    if (id==R.id.nav_link){

            Toast.makeText(getApplicationContext(), "Link", Toast.LENGTH_LONG).show();
            return true;

        }
    return true;
    }


}

Well you can try this, you will need to do some stuff manually but that's the price of doing what you want.好吧,你可以试试这个,你需要手动做一些事情,但这是做你想做的事情的代价。 This is what you need to do:这是你需要做的:

  1. Delete the implementation of the NavigationView.OnNavigationItemSelectedListener, it will be not necesary删除 NavigationView.OnNavigationItemSelectedListener 的实现,就不需要了
  2. After calling:调用后:

NavigationUI.setupWithNavController(navigationView, navController); NavigationUI.setupWithNavController(navigationView, navController);

Insert this snippet:插入此片段:

navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                int id=menuItem.getItemId();
                //it's possible to do more actions on several items, if there is a large amount of items I prefer switch(){case} instead of if()
                if (id==R.id.nav_home){
                    Toast.makeText(getApplicationContext(), "Home", Toast.LENGTH_SHORT).show();
                }
                //This is for maintaining the behavior of the Navigation view
                NavigationUI.onNavDestinationSelected(menuItem,navController);
                //This is for closing the drawer after acting on it
                drawer.closeDrawer(GravityCompat.START);
                return true;
            }
        });

I've made my own for the home fragment but you can do it with your own "link" fragment Note that variable names can change but the idea is the same我已经为主页片段制作了自己的片段,但您可以使用自己的“链接”片段来完成请注意,变量名称可以更改,但想法是相同的

You could follow two approach for this.为此,您可以采用两种方法。
First approach第一种方法
would be to use the setOnMenuItemClickListener when you want to implement listener only for a single item in the navigation drawer.当您只想为导航抽屉中的单个项目实现侦听器时,将使用setOnMenuItemClickListener This adds a listener for a single item in the navigation drawer without affecting the other navigation items.这会为导航抽屉中的单个项目添加一个侦听器,而不会影响其他导航项目。

 val navigationView: NavigationView = findViewById(R.id.nav_view) as NavigationView

    navigationView.menu!!.findItem(R.id.nav_logout).setOnMenuItemClickListener { menuItem:MenuItem? ->
        //write your implementation here
        //to close the navigation drawer
        if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
            drawer_layout.closeDrawer(GravityCompat.START)
        }
        Toast.makeText(applicationContext, "single item click listener implemented", Toast.LENGTH_SHORT).show()
        true
    }



Second Approach第二种方法
would be to use the setNavigationItemSelectedListener when you want to write listener for each item in the navigation drawer.当您想为导航抽屉中的每个项目编写侦听器时,将使用setNavigationItemSelectedListener

val navigationView: NavigationView = findViewById(R.id.nav_view) as NavigationView
 navigationView.setNavigationItemSelectedListener { menuItem ->
    when (menuItem.itemId) {
        R.id.nav_gallery -> {
            //write your implementation here
            if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
                drawer_layout.closeDrawer(GravityCompat.START)
            }
            true
        }
        else -> {
            if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
                drawer_layout.closeDrawer(GravityCompat.START)
            }
            false
        }
    }
}

For Kotlin,对于 Kotlin,

   bottom_navigation.setOnItemSelectedListener {

        when(it.itemId) {
            R.id.page_1 -> {
                // Respond to navigation item 1 click
                Toast.makeText(this,"Home Clicked",Toast.LENGTH_SHORT).show()
                true
            }
            R.id.page_2 -> {
                // Respond to navigation item 2 click
                true
            }
            R.id.page_3 -> {
                // Respond to navigation item 2 click
                true
            }
            R.id.page_4 -> {
                // Respond to navigation item 2 click
                true
            }

            else -> false
        }
    }

.OnNavigationItemSelectedListener is depricated .OnNavigationItemSelectedListener 已被贬低

Here's two ways for navigation item clicks这是导航项点击的两种方式

First Way:- if you want to show fragments after clicking on navigation drawer item, then you can follow some simple steps for this.第一种方式:-如果您想在单击导航抽屉项目后显示片段,那么您可以按照一些简单的步骤进行操作。

  • you have to create a Navigation Graph .您必须创建一个Navigation Graph for more information Click here更多信息请点击这里

  • You have to give the id of both the menu item and the fragment in Navigation Graph same.您必须为导航图中的菜单项片段提供相同的id

See this image:- Menu Item ID请参阅此图片:-菜单项 ID

See this image:- Navigation Graph - Fragment ID请参阅此图片:-导航图 - 片段 ID

DrawerLayout drawer = binding.drawerLayout;
    NavigationView navigationView = binding.navView;
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    mAppBarConfiguration = new AppBarConfiguration.Builder(
            R.id.home, R.id.gallery, R.id.nav_slideshow)
            .setOpenableLayout(drawer)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main3);
    NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
    NavigationUI.setupWithNavController(navigationView, navController);

When both id is same, then Your Navigation View will handle your navigation items clicks according to ids.当两个 id 相同时,您的导航视图将根据 id 处理您的导航项点击。

Second Way:- if you want to show custom things after clicking on navigation drawer item, then you can implement Navigation Item Click Listener.第二种方式:-如果您想在单击导航抽屉项后显示自定义内容,则可以实现导航项单击侦听器。

navigationView.setNavigationItemSelectedListener(item -> {
        if (item.getItemId()==R.id.home){
            // your code
            Toast.makeText(this, "Clicked..", Toast.LENGTH_SHORT).show();
            drawer.close();
            return true;
        }
        return false;
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM