6
Next, I would like a date selector to appear as soon as I click on editText I have, but what I found automatically setting the current date, I want it to be chosen...
Follow the code I’ve tried so far:
public class AtividadePrincipal extends AppCompatActivity {
ListView lvLista;
List<String> nomes;
EditText data1;
Calendar dateSelected = Calendar.getInstance();
private DatePickerDialog datePickerDialog;
String myFormat = "dd-MM-yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_atividade_principal);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
data1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
setDateTimeField();
// showDialog(DATE_DIALOG_ID);
return false;
}
});
private void setDateTimeField() {
Calendar newCalendar = dateSelected;
datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
dateSelected.set(year, monthOfYear, dayOfMonth, 0, 0);
data1.setText(sdf.format(dateSelected.getTime()));
}
}, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
data1.setText(sdf.format(dateSelected.getTime()));
}
}
follows the xml of editText data1:
<EditText
android:id="@+id/data1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:layout_marginTop="15dp"
android:background="@drawable/cantos_arredondados"
android:drawableRight="@drawable/icone_cor_diferente"
android:hint="Data1"
android:inputType="date"
android:paddingTop="8dp"
android:textColor="@color/colorAccent" />
worked super well! thanks
– Alan Willian Duarte
Thanks, helped me a lot. I only recommend using
OnFocusChangeListener
instead ofOnClickListener
, as I did in my application.– gabrieloliveira