我想清理我的代码并让我的复选框从 onOptionsItemSelected() 中的 switch 语句执行一些操作。相反,我的自定义复选框在 onCreateOptionsMenu 中有一个 onClick 侦听器。这可行,但我想了解如何在案例 R.id.star_favorite: 中调用代码。
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
checkBox = (CheckBox) menu.findItem(R.id.star_favorite).getActionView();
checkBox.setButtonDrawable(R.drawable.favorite_checkbox);
if(currentQuote != null) {
currentQuoteIsFavorite = currentQuote.getFavorite();
checkBox.setChecked(currentQuoteIsFavorite);
}
checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(currentQuote != null) {
currentQuoteIsFavorite = !currentQuoteIsFavorite;
updateFavorite(currentQuoteIsFavorite);
} else {
checkBox.setChecked(false);
Toast.makeText(getApplicationContext(), "No Quote To Save", Toast.LENGTH_SHORT).show();
}
}
});
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.star_favorite:
//already tried putting code like updateFavorite() inside here but it's not called
Toast.makeText(this, "Checkbox clicked", Toast.LENGTH_SHORT).show();
if(currentQuote != null) {
currentQuoteIsFavorite = !currentQuoteIsFavorite;
updateFavorite(currentQuoteIsFavorite);
} else {
checkBox.setChecked(false);
Toast.makeText(getApplicationContext(), "No Quote To Save", Toast.LENGTH_SHORT).show();
}
case R.id.share_quote:
Log.d("onOptionsItemSelected", "case R.id.share_quote selected");
shareQuote();
break;
case R.id.menu:
Log.d("onOptionsItemSelected", "case R.id.menu selected");
break;
}
return super.onOptionsItemSelected(item);
}