Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/217.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java setNavigationItemSelectedListener不工作_Java_Android_Material Design_Navigationview - Fatal编程技术网

Java setNavigationItemSelectedListener不工作

Java setNavigationItemSelectedListener不工作,java,android,material-design,navigationview,Java,Android,Material Design,Navigationview,我的NavigationViewonClick事件不起作用 下面是我一个接一个地尝试的代码片段,但没有任何效果: 使用OnClick()方法实现NavigationView.OnNavigationItemSelectedListener 设置导航项SelectedListener方法 nav = (NavigationView)findViewById(R.id.nav); nav.setNavigationItemSelectedListener(new NavigationView.On

我的
NavigationView
onClick
事件不起作用

下面是我一个接一个地尝试的代码片段,但没有任何效果:

  • 使用
    OnClick()
    方法实现
    NavigationView.OnNavigationItemSelectedListener
  • 设置导航项SelectedListener方法

    nav  = (NavigationView)findViewById(R.id.nav);
    nav.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem item) {
            Toast.makeText(getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();
            return true;
        }
    });
    
  • 使用
    OnOptionItemSelected()
    方法

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    if(toggle.onOptionsItemSelected(item))
    {
        return true;
    }
    switch (item.getItemId()) {
        case R.id.lib:
    
            Toast.makeText(getApplicationContext(),"OK",Toast.LENGTH_SHORT).show();
            return true;
    
        case R.id.fav:
            Toast.makeText(getApplicationContext(),"OK",Toast.LENGTH_SHORT).show();
    
            return true;
    }
    return super.onOptionsItemSelected(item);
    }
    
  • 我也尝试了所有这些问题和与我的问题相关的博客,但都不起作用

  • 这是我完整的MainActivity.java文件:

    public class MainActivity extends AppCompatActivity{
    
    public frag_song song;
    public frag_artist artist;
    public  frag_album album;
    public TabLayout tab;
    Uri songUri;
    Cursor songCursor;
    public static LinearLayout mainLayout;
    int songTitle,songArtist,duration,data,songAlbum;
    public NavigationView nav;
    public DrawerLayout layout;
    public ActionBarDrawerToggle toggle;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME);
        //actionBar.setIcon(R.drawable.logo);
        mainLayout = (LinearLayout)findViewById(R.id.main);
    
        //All Stuff Of NAvigatin Drawer
        layout = (DrawerLayout)findViewById(R.id.drawerL);
        toggle = new ActionBarDrawerToggle(MainActivity.this,layout,R.string.open,R.string.close);
        layout.addDrawerListener(toggle);
        toggle.syncState();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        nav  = (NavigationView)findViewById(R.id.nav);
        nav.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {
                Toast.makeText(getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();
                return true;
            }
        });//Not Working
        nav.setItemIconTintList(null);
    
        //check if app open first time or not
        SharedPreferences prefs = this.getSharedPreferences("com.blackhat.rhythmbox", Context.MODE_PRIVATE);
        Boolean first = prefs.getBoolean("first", true);
        if(first){
            //Adding song To  Database
            addtoDatabase();
            prefs.edit().putBoolean("first",false).commit();
        }
    
        //Decaring Object of Fragment
        //TO access Tab
        tab = (TabLayout)findViewById(R.id.tabs);
        song = new frag_song();
        artist = new frag_artist();
        album = new frag_album();
    
    
        //addding tab to tab layout
        tab.addTab(tab.newTab().setText("Songs"),true);
        tab.addTab(tab.newTab().setText("ALbum"));
        tab.addTab(tab.newTab().setText("Artist"));
    
        tab.getTabAt(0).setIcon(R.drawable.icons_song);
        tab.getTabAt(1).setIcon(R.drawable.icons_album);
        tab.getTabAt(2).setIcon(R.drawable.icon_artist);
        //setting default tab
            FragmentManager fm = getSupportFragmentManager();
            fm.beginTransaction().replace(R.id.frame_container,song).commit();
    
            //on tab select
            tab.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    switch (tab.getPosition())
                    {
                        case 0 :
                            FragmentManager f_song = getSupportFragmentManager();
                            f_song.beginTransaction().replace(R.id.frame_container,song).commit();
                            break;
    
                        case 1 :
                            FragmentManager f_artist = getSupportFragmentManager();
                            f_artist.beginTransaction().replace(R.id.frame_container,album).commit();
                            break;
    
                        case 2 :
                            FragmentManager f_album = getSupportFragmentManager();
                            f_album.beginTransaction().replace(R.id.frame_container,artist).commit();
                            break;
                    }
    
                }
    
                @Override
                public void onTabUnselected(TabLayout.Tab tab) {
    
                }
    
                @Override
                public void onTabReselected(TabLayout.Tab tab) {
    
                }
            });
        }
    
    @Override
    protected void onStop() {
        super.onStop();
    }
    
    public void addtoDatabase(){
        song_db dbHelper = new song_db(getApplicationContext());
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
    
        ContentResolver contentResolver = getContentResolver();
        songUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        songCursor = contentResolver.query(songUri, null, null, null, null);
        //checking if cursor is null or not
    
        if(songCursor !=null && songCursor.moveToFirst()){
            songTitle = songCursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
            songArtist = songCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
            duration = songCursor.getColumnIndex(MediaStore.Audio.Media.DURATION);
            songAlbum = songCursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
            data = songCursor.getColumnIndex(MediaStore.Audio.Media.DATA);
            Toast.makeText(getApplicationContext(),"Loaded",Toast.LENGTH_SHORT).show();
            do{
                contentValues.put("name",songCursor.getString(songTitle));
                contentValues.put("artist",songCursor.getString(songArtist));
                contentValues.put("album",songCursor.getString(songAlbum));
                contentValues.put("path",songCursor.getString(data));
                contentValues.put("duration",songCursor.getString(duration));
                contentValues.put("isfavorite",0);
                contentValues.put("playlist","regular");
                // contentValues.put("name",songCursor.getString(songArtist));
                db.insert("songs",null,contentValues);
            }while (songCursor.moveToNext());
        }
    
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(toggle.onOptionsItemSelected(item))
        {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    

    }

    如果您遇到更多问题并想了解导航抽屉的内容,请创建一个新项目,然后选择导航抽屉布局或签出以下代码:

    使用以下代码:

    import android.os.Bundle;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.Snackbar;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentTransaction;
    import android.view.View;
    import android.support.design.widget.NavigationView;
    import android.support.v4.view.GravityCompat;
    import android.support.v4.widget.DrawerLayout;
    import android.support.v7.app.ActionBarDrawerToggle;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.view.Menu;
    import android.view.MenuItem;
    
    public class MainActivity extends AppCompatActivity
            implements NavigationView.OnNavigationItemSelectedListener {
    
        @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.setDrawerListener(toggle);
            toggle.syncState();
    
            NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
            navigationView.setNavigationItemSelectedListener(this);
    
            //add this line to display menu1 when the activity is loaded
            displaySelectedScreen(R.id.nav_menu1);
        }
    
        @Override
        public void onBackPressed() {
            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            if (drawer.isDrawerOpen(GravityCompat.START)) {
                drawer.closeDrawer(GravityCompat.START);
            } else {
                super.onBackPressed();
            }
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
    
            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }
    
            return super.onOptionsItemSelected(item);
        }
    
        private void displaySelectedScreen(int itemId) {
    
            //creating fragment object
            Fragment fragment = null;
    
            //initializing the fragment object which is selected
            switch (itemId) {
                case R.id.nav_menu1:
                    fragment = new Menu1();
                    break;
                case R.id.nav_menu2:
                    fragment = new Menu2();
                    break;
                case R.id.nav_menu3:
                    fragment = new Menu3();
                    break;
            }
    
            //replacing the fragment
            if (fragment != null) {
                FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                ft.replace(R.id.content_frame, fragment);
                ft.commit();
            }
    
            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
        }
    
    
        @SuppressWarnings("StatementWithEmptyBody")
        @Override
        public boolean onNavigationItemSelected(MenuItem item) {
    
            //calling the method displayselectedscreen and passing the id of selected menu
            displaySelectedScreen(item.getItemId());
            //make this method blank
            return true;
        }
    
    
    }
    

    我也有同样的问题,我发现Android对XML的布局非常挑剔。我将NavigationView作为抽屉布局的第一个孩子,但出于愚蠢的原因,它必须是最后一个孩子。因此,布局中的元素必须按以下顺序排列:

    <DrawerLayout>
        <FrameLayout/>
        <NavigationView/>
    </DrawerLayout>
    
    <DrawerLayout>
        <NavigationView/>
        <FrameLayout/>
    </DrawerLayout>
    
    
    
    不按此顺序:

    <DrawerLayout>
        <FrameLayout/>
        <NavigationView/>
    </DrawerLayout>
    
    <DrawerLayout>
        <NavigationView/>
        <FrameLayout/>
    </DrawerLayout>
    

    这对我来说很管用,可以把视野带到最前面

    navigationView.setNavigationItemSelectedListener(this);
    navigationView.bringToFront();
    

    我试着用android studio创建一个新项目,并将它完美地实现。我应该添加整个java文件和XML文件吗?是的,你可以根据需要进行编码@RohitChauhanIt正在工作,谢谢ManI花了三天时间寻找这个解决方案,谢谢,我希望谷歌能阅读并更新他们的文档WTF android。谢谢你的帮助。我用Android Studio创建了一个新项目,我选择了“导航抽屉”,直到我看到你的帖子它才会工作。你救了我的命,伙计!谢谢你!2019年10月10日,和Studio自动生成的代码仍在使用。唉!它对我来说很有用navigationView.bringToFront();setupDrawerContent(导航视图);