I would like to know how to optimize a large string of ifs so that the code is more efficient and readable.
My Android application uses version 2.3.3 (API 10), in this application I have an activity responsible for displaying user account information, where it can edit this information and update. This activity contains 8 fields next to the field has 1 "Edit" button and a hidden "OK" button, if the "Edit" button is clicked then the application hides the "Edit" and displays the "OK" in the same place. That way I have the total 16 buttons, 8 "Edit" and 8 "OK". That left my onClick method (View v) with 16 ifs.
How can I improve this and make it more efficient and more readable? I know I can use the switch that would be almost the same thing.
The code below has the method with only 2 of the 16 buttons to simplify, since the other buttons follow the same logic.
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == R.id.btneditar1) {
camponome.setSelectAllOnFocus(true);
camponome.setFocusable(true);
camponome.setFocusableInTouchMode(true);
camponome.requestFocus();
imm.showSoftInput(camponome, InputMethodManager.SHOW_FORCED);
btneditar1.setVisibility(View.GONE);
btnok1.setVisibility(View.VISIBLE);
}
if(v.getId() == R.id.btnok1) {
CampoValido = ValidaCampo.validateNotNull(camponome, "Campos sem dados são inválidos!");
if(CampoValido) {
CampoValido = ValidaCampo.validateNotEqual(camponome, bnome);
if(CampoValido) {
final String nome = camponome.getText().toString().trim();
atualizar.execute(usuario, nome, null, null, null, null, null, null);
txtnomebd.setText(nome);
}
camponome.setFocusable(false);
camponome.setFocusableInTouchMode(false);
camponome.requestFocus();
btnok1.setVisibility(View.GONE);
btneditar1.setVisibility(View.VISIBLE);
}
}
if(v.getId() == R.id.btneditar2) {
camposobrenome.setSelectAllOnFocus(true);
camposobrenome.setFocusable(true);
camposobrenome.setFocusableInTouchMode(true);
camposobrenome.requestFocus();
imm.showSoftInput(camposobrenome, InputMethodManager.SHOW_FORCED);
btneditar2.setVisibility(View.GONE);
btnok2.setVisibility(View.VISIBLE);
}
if(v.getId() == R.id.btnok2) {
CampoValido = ValidaCampo.validateNotNull(camposobrenome, "Campos sem dados são inválidos!");
if(CampoValido) {
CampoValido = ValidaCampo.validateNotEqual(camposobrenome, bsobrenome);
if(CampoValido) {
final String sobrenome = camposobrenome.getText().toString().trim();
atualizar.execute(usuario, null, sobrenome, null, null, null, null, null);
txtsobrenomebd.setText(sobrenome);
}
camposobrenome.setFocusable(false);
camposobrenome.setFocusableInTouchMode(false);
camposobrenome.requestFocus();
btnok2.setVisibility(View.GONE);
btneditar2.setVisibility(View.VISIBLE);
}
}
}