I am trying to do some validation of an editText field, allow me to elaborate because I am using a bunch of concepts that all have their own questions in stackOverflow but I have the feeling that what I'm trying to do is not yet answered in any of them, and this is something rather basic so either I'm screwing up badly or I just found a bug, also, many of the popular questions and answers are a couple of years old...
I have two Edittext fields which contain an initial date and a termination date which are input from a datepicker, I am validating that after the termination date has been input by the datepicker this date happens after the initial date, and that if it doesn't it displays an error using setError.
So far so good, I manage to do all that but there is something bothering me:
When I first click on the EditText
it does nothing (because I use setInputType(InputType.TYPE_NULL)
along with android:focusableInTouchMode="true"
in the XML; to avoid showing me the keyboard, so it clicks, get selected, and no keyboard, but also no datepicker, until you click again, then the onClick method triggers the datepicker and all works as intended.)
I was going to show you images but I don't have the rep points :/
If I use setFocusable(false)
, something weird happens, when the setError comes up only the icon shows without the text.
If I don't use setFocusable(false)
, the editText appears as selected when the activity starts (no cursor flashing because I disabled input) and stays selected (it stays blue but you can click anywhere)
If I don't want it to be selected at start I use android:focusableInTouchMode="true
" in the XML in the parent layout, per recommendation of this question (Stop EditText from gaining focus at Activity startup) and that solves that problem. But I have the first click and nothing happens second click and shows the datepicker problem again... what am I doing wrong.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="#FFFFFF"
android:layout_height="match_parent"
android:gravity="center_vertical"
style="@style/AppTheme"
android:id="@+id/fechasalariolayout"
android:focusableInTouchMode="true">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAlignment="center"
android:inputType="date"
android:ems="10"
android:gravity="center_horizontal"
android:onClick="showDatePickerDialogFT"
android:id="@+id/fechaterminacioninpt"
android:layout_weight="10"
android:layout_gravity="center_horizontal" />
public class fechaSalario extends ActionBarActivity {
private Button calcularbtn;
static EditText fechaingresoinpt, fechaterminacioninpt, salarioinpt;
public static boolean isFechaInicial, isFechaTerminacion = false;
private RadioGroup sueldoPeriodo, salarioMin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//set content view AFTER ABOVE sequence (to avoid crash)
this.setContentView(R.layout.fechasalario);
calcularbtn = (Button) findViewById(R.id.calcularbtn);
fechaingresoinpt = (EditText) findViewById(R.id.fechaingresoinpt);
fechaterminacioninpt = (EditText) findViewById(R.id.fechaterminacioninpt);
salarioinpt = (EditText) findViewById(R.id.salarioinpt);
sueldoPeriodo = (RadioGroup)findViewById(R.id.sueldoperiodo);
salarioMin = (RadioGroup) findViewById(R.id.salariomin);
fechaterminacioninpt.setInputType(InputType.TYPE_NULL);
//fechaterminacioninpt.setFocusable(false);
//OnChangeTxtListener
fechaterminacioninpt.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
fechaterminacioninpt.setError(null);
validarFechaTerminacion(fechaterminacioninpt, fechaingresoinpt); // pass your EditText Obj here.
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
public void onClickCalcular(View view) {
//Llamar a una funcion calcular que llame a un activity para desplegar.
// Enviar BUNDLE
//Verificar que los datos hayan sido introducidos correctamente.
//verificar fechas y cantidades válidas.
//verificar que todos los radio buttons esten seleccionados
Intent intent = new Intent(this, calcular.class);
Bundle variables = new Bundle();
variables = getIntent().getExtras();
RadioButton sueldoperiodo = (RadioButton)this.findViewById(sueldoPeriodo.getCheckedRadioButtonId());
RadioButton salariomin = (RadioButton)this.findViewById(salarioMin.getCheckedRadioButtonId());
//validar Fecha inicial menor a fecha de terminación
variables.putString("FECHA_INICIO", String.valueOf(fechaingresoinpt.getText()));
variables.putString("FECHA_TERMINACION", String.valueOf(fechaterminacioninpt.getText()));
variables.putString("SALARIO", String.valueOf(salarioinpt.getText()));
variables.putString("SUELDO_PERIODO", sueldoperiodo.getText().toString());
variables.putString("SALARIO_MIN", salariomin.getText().toString());
intent.putExtras(variables);
startActivity(intent);
}
public void validarFechaTerminacion(EditText edt, EditText edt2){
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
DateTime fechaInicio = formatter.parseDateTime(String.valueOf(fechaingresoinpt.getText()));
DateTime fechaTerm = formatter.parseDateTime(String.valueOf(fechaterminacioninpt.getText()));
if (fechaInicio.isAfter(fechaTerm)){
/* fechaterminacioninpt.requestFocus();*/
fechaterminacioninpt.setError("La fecha de terminación ocurre antes que la fecha de inicio");
}
else{
// Do nothing
fechaterminacioninpt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus){
fechaterminacioninpt.setError(null);
}
});
}
//validar cantidad es un numero monetario válido
//validar cantidad es un numero entero válido
// validar radio buttons han sido seleccionados.
}
public void showDatePickerDialogFI(View v) {
isFechaInicial = true;
isFechaTerminacion = false;
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
public void showDatePickerDialogFT(View v) {
isFechaTerminacion = true;
isFechaInicial = false;
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
}