简体   繁体   中英

How to change activities within a Navigation Drawer Activity

I'm trying to create a button that will open another activity within my Navigation Drawer view. This is a part of my code and it stops working when I hit the button. How can I fix this?

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

        Button greetings_button = (Button) findViewById(R.id.greetings_lesson);
        greetings_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, GreetingsLesson.class));
            }
        });

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

You need to do this in onNavigationItemSelected override method that you implemented :

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()) {
       case R.id.greetings_lesson: {
            startActivity(new Intent(MainActivity.this, GreetingsLesson.class));
            break;
        }  
    }
    return true;
}

And remove this section of code :

Button greetings_button = (Button) findViewById(R.id.greetings_lesson);
greetings_button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        startActivity(new Intent(MainActivity.this, GreetingsLesson.class));
    }
});

Then put this code instead :

    NavigationView navigationView = (NavigationView) findViewById(R.id.YOUR_NAVIGATION_VIEW_ID);
navigationView.setNavigationItemSelectedListener(this);

Replace your navigation view id with 'YOUR_NAVIGATION_VIEW_ID'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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