butStart = findViewById(R.id.butStart); buttonClick1();
SharedPreferences save = getSharedPreferences("Save", MODE_PRIVATE);
level = save.getInt("Level", 0);
}
private ImageButton butStart;
int level;
public void buttonClick1() {
butStart.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (level) {
case 0:
try {
Intent intent = new Intent(MainActivity.this, go1.class);
startActivity(intent);
finish();
} catch (Exception e) {//
}
break;
case 1:
try {
Intent intent = new Intent(MainActivity.this, go2.class);
startActivity(intent);
finish();
} catch (Exception e) { //
}
break;
case 2:
try {
Intent intent = new Intent(MainActivity.this, go3.class);
startActivity(intent);
finish();
} catch (Exception e) { //
}
break;
default: break;
}
}
});
switch (level) {
case 1:
butStart.setVisibility(View.GONE);
break;
default:
butStart.setVisibility(View.VISIBLE);
break;
}
}
Hello. I want the button "butStart" to disappear depending on a case state. I tried make it onn my own, but it's either appears, or never shows again. "if/else" structure didnt work My intention is to make 'continue' button, for a user to resume the session in the app.
CodePudding user response:
The issue is that you are calling your switch statement only one time i.e. in buttonClick1() moreover, you are calling the method before assigning the value to variable of level,
Try
butStart = findViewById(R.id.butStart);
SharedPreferences save = getSharedPreferences("Save", MODE_PRIVATE);
level = save.getInt("Level", 0);
buttonClick1();
}
private ImageButton butStart;
int level;
public void buttonClick1() {
butStart.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (level) {
case 0:
try {
Intent intent = new Intent(MainActivity.this, go1.class);
startActivity(intent);
finish();
} catch (Exception e) {//
}
break;
case 1:
try {
Intent intent = new Intent(MainActivity.this, go2.class);
startActivity(intent);
finish();
} catch (Exception e) { //
}
break;
case 2:
try {
Intent intent = new Intent(MainActivity.this, go3.class);
startActivity(intent);
finish();
} catch (Exception e) { //
}
break;
default: break;
}
}
});
switch (level) {
case 1:
butStart.setVisibility(View.GONE);
break;
default:
butStart.setVisibility(View.VISIBLE);
break;
}
}
Moreover, in the switch, you have made the only case for value '1' even if the value is '0' the default case will be called the visibility of the button will be set as Visibile and at value 1 it is for sure GONE. Let me clear up one more thing your switch statement will be called for only one time in the above scenario.
Above is the solution for what I've understood your problem. If you didn't get the expected result then kindly update the question or you may ask in a comment with a complete clarification of what result you want and what you are getting now.