Reputation: 9
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();
}
});
}
}
Upvotes: 0
Views: 61
Reputation: 542
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'
Upvotes: 1