I repeat this code up to 4 times, once for each button (bt1, bt2, bt3 and bt4). It only changes where it says bt1 that I replace it with the other buttons.
Surely there is a way to reduce the code so as not to repeat the same thing 4 times. Can you help me?
bt1.setOnClickListener(new AdapterView.OnClickListener() {
@Override
public void onClick( View view) {
//Toast.makeText(SumasActivity.this, "1: "+bt1.getText()+" 2: "+ (n1 + n2), Toast.LENGTH_SHORT).show();
if (bt1.getText().equals("" + (n1 + n2))) {
bt1.setBackgroundColor(Color.parseColor("#5fba7d"));
} else {
bt1.setBackgroundColor(Color.parseColor("#f48024"));
}
// DELAY y PASA PANTALLA
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if(stage>=5) {
Intent i = new Intent(SumasActivity.this, Inicio.class);
i.putExtra("dificultad", dificultad);
i.putExtra("stage", stage);
startActivity(i);
}else{
Intent i = new Intent(SumasActivity.this, SumasActivity.class);
i.putExtra("dificultad", dificultad);
i.putExtra("stage", stage);
startActivity(i);
}
}
}, 2000);
This could help you, try it and comment your results.
Function that returns the OnClick listener.
This function you pass to the button in its setOnClickListener method
You have 2 options:
Use subclasses, passing the specific button as a parameter to the listener
Just extract the common logic into a method