英文:
Android onMenuItemClick receiving wrong item
问题
我有一个菜单,当我创建它时,它可以正常弹出。
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/day"
android:title="Day" />
<item
android:id="@+id/week"
android:title="Week" />
<item
android:id="@+id/month"
android:title="Month" />
<item
android:id="@+id/year"
android:title="Year" />
</menu>
出于某种原因,onMenuItemClick
只会在我点击任何项时返回 "Year"。这是一个非常奇怪的问题,我不知道为什么会发生。
public void showMenu(View v) {
PopupMenu popup = new PopupMenu(getContext(), v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.date_range_menu, popup.getMenu());
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.day:
((MainActivity) requireActivity()).toast("Day");
changeDateRange(DateRange.DAY);
case R.id.week:
((MainActivity) requireActivity()).toast("Week");
changeDateRange(DateRange.WEEK);
case R.id.month:
((MainActivity) requireActivity()).toast("Month");
changeDateRange(DateRange.MONTH);
case R.id.year:
((MainActivity) requireActivity()).toast("Year");
changeDateRange(DateRange.YEAR);
default:
return false;
}
}
});
}
英文:
I have this menu that pops up fine when I create it.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/day"
android:title="Day" />
<item
android:id="@+id/week"
android:title="Week" />
<item
android:id="@+id/month"
android:title="Month" />
<item
android:id="@+id/year"
android:title="Year" />
</menu>
For some reason, the onMenuItemClick
is only giving me "Year" no matter which item I click on. This is a really strange problem and I have no idea why it's happening.
public void showMenu(View v) {
PopupMenu popup = new PopupMenu(getContext(), v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.date_range_menu, popup.getMenu());
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.day:
((MainActivity) requireActivity()).toast("Day");
changeDateRange(DateRange.DAY);
case R.id.week:
((MainActivity) requireActivity()).toast("Week");
changeDateRange(DateRange.WEEK);
case R.id.month:
((MainActivity) requireActivity()).toast("Month");
changeDateRange(DateRange.MONTH);
case R.id.year:
((MainActivity) requireActivity()).toast("Year");
changeDateRange(DateRange.YEAR);
default:
return false;
}
}
});
}
答案1
得分: 1
需要在每个case语句中添加break;
关键字。
英文:
You need to add the break;
keyword to each case.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论