How to pick a time when clicking on edit text?
In the android studio, we will create a time picker dialog to choose a time when clicking on edit text.
We will pick a specific time using java in android studio.
first, we will create a new project named anything.
activity_main.xml
Type this code In activity_main.xml file
MainActivity.java
watch video
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/edtdate" android:ems="15" android:inputType="time" android:hint="00:00" android:focusable="false"/> </LinearLayout>
In MainActivity.java file type this java code
package com.example.selecttime; import androidx.appcompat.app.AppCompatActivity; import android.app.TimePickerDialog; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TimePicker; import java.util.Calendar; public class MainActivity extends AppCompatActivity implements View.OnClickListener { EditText selectTime; private int mHour, mMinute; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate ( savedInstanceState ); setContentView ( R.layout.activity_main ); selectTime = findViewById ( R.id.edtdate ); selectTime.setOnClickListener ( this ); } @Override public void onClick(View v) { if (v == selectTime) { //get time final Calendar calendar = Calendar.getInstance (); mHour = calendar.get ( Calendar.HOUR ); mMinute = calendar.get ( Calendar.MINUTE ); //launch picker dialog TimePickerDialog timePickerDialog = new TimePickerDialog ( this, new TimePickerDialog.OnTimeSetListener () { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { selectTime.setText ( hourOfDay + ":" + minute ); } }, mHour, mMinute, false ); timePickerDialog.show (); } } }
https://youtu.be/7yYaSbhS0W8