step 1:
public class MainActivity extends AppCompatActivity implements View.OnClickListener { Button btnDatePicker, btnTimePicker; EditText txtDate, txtTime; private int mYear, mMonth, mDay, mHour, mMinute; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnDatePicker=(Button)findViewById(R.id.btn_date); btnTimePicker=(Button)findViewById(R.id.btn_time); txtDate=(EditText)findViewById(R.id.in_date); txtTime=(EditText)findViewById(R.id.in_time); btnDatePicker.setOnClickListener(this); btnTimePicker.setOnClickListener(this); } @Override public void onClick(View v) { if (v == btnDatePicker) { // Get Current Date
final Calendar c = Calendar.getInstance(); mYear = c.get(Calendar.YEAR); mMonth = c.get(Calendar.MONTH); mDay = c.get(Calendar.DAY_OF_MONTH); DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { @Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { txtDate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year); } }, mYear, mMonth, mDay);
datePickerDialog.show(); }
. if (v == btnTimePicker) { // Get Current Time
final Calendar c = Calendar.getInstance(); mHour = c.get(Calendar.HOUR_OF_DAY); mMinute = c.get(Calendar.MINUTE); // Launch Time Picker Dialog
TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() { @Override
public void onTimeSet(TimePicker view, int hourOfDay,int minute) { txtTime.setText(hourOfDay + ":" + minute); } }, mHour, mMinute, false); timePickerDialog.show(); } }
//https://www.codeproject.com/Articles/1112812/Android-Alert-Dialog-Tutorial-Working-with-Time-Pi
step 2:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"> <EditTextandroid:layout_width="200dp"android:layout_height="wrap_content"android:id="@+id/in_date"android:layout_marginTop="82dp"android:layout_alignParentTop="true"android:layout_alignParentLeft="true"android:layout_alignParentStart="true" /> <Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="SELECT DATE"android:id="@+id/btn_date"android:layout_alignBottom="@+id/in_date"android:layout_toRightOf="@+id/in_date"android:layout_toEndOf="@+id/in_date" /> <EditTextandroid:layout_width="200dp"android:layout_height="wrap_content"android:id="@+id/in_time"android:layout_below="@+id/in_date"android:layout_alignParentLeft="true"android:layout_alignParentStart="true" /> <Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="SELECT TIME"android:id="@+id/btn_time"android:layout_below="@+id/btn_date"android:layout_alignLeft="@+id/btn_date"android:layout_alignStart="@+id/btn_date" /> </RelativeLayout>
No comments:
Post a Comment