I would like to clean up my code and have my checkbox do some actions from the switch statement inside onOptionsItemSelected(). Instead, I have an onClick listener in onCreateOptionsMenu for my custom checkbox. This works, but I would like to understand how to have code inside case R.id.star_favorite: called.
@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);
}
Aucun commentaire:
Enregistrer un commentaire