@Override
public boolean onOptionsItemSelected(MenuItem item) {
Boolean set = false;
switch (item.getItemId()){
case R.id.background1:
mainLayout.setBackgroundResource(R.drawable.redpinkgradientbackground);
set = true;
if (set){
Toast.makeText(getApplicationContext(), "Background already set", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Background set", Toast.LENGTH_SHORT).show();
}
return true;
case R.id.background2:
mainLayout.setBackgroundResource(R.drawable.redgradientbackground);
set = true;
if (set){
Toast.makeText(getApplicationContext(), "Background already set", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Background set", Toast.LENGTH_SHORT).show();
}
return true;
case R.id.background3:
mainLayout.setBackgroundResource(R.drawable.greengradientbackground);
return true;
case R.id.background4:
mainLayout.setBackgroundResource(R.drawable.blackgreygradientbackground);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
我试图让用户知道什么时候设置了背景,所以当有人选择背景时,它会显示一个带有文本的祝酒词,它已经被设置为背景' ,当选择另一个背景时,会显示文本'背景设置'但是当我尝试使用布尔值时,在case语句中设置为true但是当我在我的尝试中它只显示2个吐司应用
答案 0 :(得分:0)
试试
private int selectedBackgroundId = -1;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.background1:
mainLayout.setBackgroundResource(R.drawable.redpinkgradientbackground);
if (selectedBackgroundId == R.id.background1){
Toast.makeText(getApplicationContext(), "Background already set", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Background set", Toast.LENGTH_SHORT).show();
}
selectedBackgroundId = R.id.background1;
return true;
case R.id.background2:
mainLayout.setBackgroundResource(R.drawable.redgradientbackground);
if (selectedBackgroundId == R.id.background2){
Toast.makeText(getApplicationContext(), "Background already set", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Background set", Toast.LENGTH_SHORT).show();
}
selectedBackgroundId = R.id.background2;
return true;
case R.id.background3:
mainLayout.setBackgroundResource(R.drawable.greengradientbackground);
if (selectedBackgroundId == R.id.background3){
Toast.makeText(getApplicationContext(), "Background already set", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Background set", Toast.LENGTH_SHORT).show();
}
selectedBackgroundId = R.id.background3;
return true;
case R.id.background4:
mainLayout.setBackgroundResource(R.drawable.blackgreygradientbackground);
if (selectedBackgroundId == R.id.background4){
Toast.makeText(getApplicationContext(), "Background already set", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Background set", Toast.LENGTH_SHORT).show();
}
selectedBackgroundId = R.id.background4;
return true;
default:
return super.onOptionsItemSelected(item);
}
}
不是很优雅,但会做到这一点。