我正在尝试创建一个按钮,该按钮将在“导航抽屉”视图中打开另一个活动。这是我的代码的一部分,当我按下按钮时它将停止工作。我该如何解决?
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();
}
});
}
}
答案 0 :(得分:1)
您需要在实现的onNavigationItemSelected覆盖方法中执行此操作:
@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;
}
并删除此部分代码:
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));
}
});
然后输入以下代码:
NavigationView navigationView = (NavigationView) findViewById(R.id.YOUR_NAVIGATION_VIEW_ID);
navigationView.setNavigationItemSelectedListener(this);
将导航视图ID替换为“ YOUR_NAVIGATION_VIEW_ID”