Search code examples
javaandroidxmlandroid-developer-api

Date Picker In Edit Text - What's wrong in this code?


I tried running it, but the Edit Text View gave no respond on clicking. The Date Picker was not even opened. What is wrong in here?

Please do help me with an elaborated answer along with the full code since I'm a newbie. Thanks

XML

<EditText
    android:id="@+id/add_date"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="32dp"
    android:layout_marginLeft="32dp"
    android:layout_marginTop="16dp"
    android:ems="10"
    android:hint="Enter Date"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/add" />

MainActivity

public class addScreen extends AppCompatActivity {

EditText dateFormat;
int year, month, day;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_screen);

    {
        dateFormat = findViewById(R.id.add_date);
        final Calendar calendar = Calendar.getInstance();
        dateFormat.setOnClickListener(v -> {
            year = calendar.get(Calendar.YEAR);
            month = calendar.get(Calendar.MONTH);
            day = calendar.get(Calendar.DAY_OF_MONTH);
            DatePickerDialog datePickerDialog = new DatePickerDialog(addScreen.this, (view, year, month, dayOfMonth) -> dateFormat.setText(SimpleDateFormat.getDateInstance().format(calendar.getTime())), year, month, day);
            datePickerDialog.show();
        });
    }
}

}


Solution

  • As Ben P said in the comment above, EditText is focusable by default.

    So if you want to stop it from being shown the keyboard and just listen to the click listener you may need to stop the focus this below line do this so add it EditText declaration in your xml

    android:focusable="false"
    

    and that's it your EditText now can listen to your click listener.

    P.S. I would recommend for you to use the material TextInputLayout and TextInputEditText which has a great look and follows the modern UX when it comes to create and input field and shown it to your users.