Objective
Since most of the Android beginner's tutorial doesn't teach you how to choose time, beginners encounter this kind of inevitable will be a bit overwhelmed, should let the user enter the date time? Not to say that the user experience is not good, processing users to enter a variety of date format will also take a great deal of effort, below to see how to achieve the Android selection time function.
Operating Effects in Android 6.0
Introduction to Timepickerdialog and Datepickerdialog
The system encapsulates two classes that we can call directly to select the TimepickerDialog
time to select the DatePickerDialog
date.
The construction method of Timepikckerdialog
Public Timepickerdialog (context context, Ontimesetlistener Listener, int hourofday, int minute, Boolean is24hourview)
1. The first parameter accepts a context message
2. The second parameter is the callback interface that executes when the selection time completes
3, the third parameter and the fourth parameter are initialized time
4, the fourth parameter select True to represent the 24-hour system, false represents 12-hour system
Datepickerdialog Construction Method
Public Datepickerdialog (context context, Ondatesetlistener CallBack, int year, int monthofyear, int dayofmonth)
1. The first parameter accepts context information
2. The second parameter is the return interface after the date selection completes
3, the last three parameters are initialized date of year
We can see that the two methods of construction are basically different, because both are inherited from AlertDialog
, so the two objects after the call to their show()
method can be the selection box pop-up.
Concrete implementation
There are two ways to implement this, one that is used directly in Activity
, and one that is FragmentDialog
used.
The direct use of the activity is relatively simple, but the code will be more chaotic, through the Fragmentdialog management of the use of the way will be more elegant, and easy to manage.
Use directly in activity
Layout file, inside a textview to display the selected time
<?xml version= "1.0" encoding= "Utf-8"?> <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= "com.example.testdemo.TestActivity" >
< TextView
android:layout_centerinparent= "true"
android:textsize= "20sp"
android:id= "@+id/time_text"
android:text= "Click this selection time"
android:layout_width= "wrap_content"
android:layout_height= "Wrap_content" />
</RelativeLayout>
Activity file:
public class Testactivity extends Appcompatactivity {private TextView timetext;
@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (r.layout.activity_test);
Timetext = (TextView) Findviewbyid (R.id.time_text); Set Click event for TextView timetext.setonclicklistener (new View.onclicklistener () {@Override public void OnClick (V
Iew v) {//Timetext incoming for display of the selected time Showdialogpick ((TextView) v);
}
}); ///Dialog Two selection times in this function private void Showdialogpick (final TextView timetext) {final StringBuffer time = new Stri
Ngbuffer ();
Gets the calendar object that is used to get the current time final Calendar calendar = Calendar.getinstance ();
int year = Calendar.get (calendar.year);
int month = Calendar.get (calendar.month);
int day = Calendar.get (calendar.day_of_month);
int hour = Calendar.get (Calendar.hour_of_day);
int minute = Calendar.get (Calendar.minute);
Instantiating a Timepickerdialog object Final Timepickerdialog Timepickerdialog = new Timepickerdialog (testactivity.this, New Timepickerdialog.ontimesetliste
NER () {//The callback function is invoked after the time of the selection @Override public void Ontimeset (timepicker view, int hourofday, int minute) {
Time.append ("" + Hourofday + ":" + minute);
Set TextView to display the time Timetext.settext the final selection;
}, hour, minute, true); Instantiate the Datepickerdialog object Datepickerdialog datepickerdialog = new Datepickerdialog (testactivity.this, New DatePickerDia Log. Ondatesetlistener () {//The callback function is invoked after the date is selected @Override public void Ondateset (DatePicker view, int years, int mo nthofyear, int dayofmonth) {//Because monthofyear will be less than the actual month January so this is going to add 1 time.append (year + "-" + (monthofyear+1) + "-
"+ DayOfMonth);
Select the time after the Date pop-up selection dialog box Timepickerdialog.show ();
}, year, month, day);
Pop-up Select Date dialog box Datepickerdialog.show (); }
}
Here, click to run to see the effect:
Use by Fragmentdialog
Why do you use Dialogfragment?
1, use the Dialogfragment Management dialog box is the official promotion use way.
2, use the Dialogfragment Management dialog box is also convenient code reuse.
Implementing Steps through Fragmentdialog
Datepickerfragment class:
public class Datepickerfragment extends Dialogfragment implements datepickerdialog.ondatesetlistener{private String da
Te @Override public Dialog Oncreatedialog (Bundle savedinstancestate) {//Get the Calendar class instance to get the current time calendar calendar
Calendar.getinstance ();
int year = Calendar.get (calendar.year);
int month = Calendar.get (calendar.month);
int day = Calendar.get (calendar.day_of_month); Returns the Datepickerdialog object//Because the Ondatesetlistener interface is implemented, the second argument is passed directly to the This return new Datepickerdialog (Getactivity (), this,
Year, month, day); }//Implement the Ondatesetlistener Interface Ondateset () method @Override public void Ondateset (DatePicker view, int year, int monthofyear, int dayofmonth) {//This way the fragment of the selection time and the fragment of the selection date are completely bound together//when used simply call the Datepickerfragment Show () method//To select the end
Select time after date timepickerfragment timepicker = new Timepickerfragment ();
Timepicker.show (Getfragmentmanager (), "Time_picker"); Upload the date selected by the user to Timepickerfragment date = year + "Years" + (monthofyear+1) + "Month" + DayOfMonth + "Day";
Timepicker.settime (date); }
}
timepickerfragment class:
Implement Ontimesetlistener interface public class Timepickerfragment extends Dialogfragment implements
timepickerdialog.ontimesetlistener{private String time = ""; @Override public Dialog Oncreatedialog (Bundle savedinstancestate) {//New Calendar class to get current time calendar calendar = Calendar
. getinstance ();
int hour = Calendar.get (Calendar.hour_of_day);
int minute = Calendar.get (Calendar.minute); Returns the Timepickerdialog object//Because the Ontimesetlistener interface is implemented, the second argument is passed directly to the This return new Timepickerdialog (Getactivity (), this,
Hour, minute, true);
///Implement Ontimesetlistener Ontimeset method @Override public void Ontimeset (timepicker view, int hourofday, int minute) {
To determine if an activity is an instance of Datacallback if (getactivity () instanceof Datacallback) {//Convert activity strong to Datacallback
Datacallback Datacallback = (datacallback) getactivity ();
Time = time + Hourofday + "point" + Minute + "min";
Call the activity's GetData method to return the data back to the activity display Datacallback.getdata (time); }} public void SetTime (String date) {time = date; }
}
the activity's layout file , with only one textview to display the time
<?xml version= "1.0" encoding= "Utf-8"?> <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= "com.example.testdemo.TestActivityActivity" >
<textview
android:id= "@+id/time_text"
android:layout_centerinparent= "true"
android:text= " Click this selection time "
android:textsize=" 20sp "
android:layout_width=" wrap_content "
android:layout_height=" wrap _content "/>
</RelativeLayout>
Activity file:
/implementation Datacallback interface to implement communication with fragment public class Testactivityactivity extends
Appcompatactivity implements datacallback{TextView timetext;
@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.LAYOUT.ACTIVITY_TEST2);
Timetext = (TextView) Findviewbyid (R.id.time_text); Set Click event for Timetext Timetext.setonclicklistener (new View.onclicklistener () {@Override public void OnClick (V
Iew v) {//Instantiate object Datepickerfragment datepickerfragment = new Datepickerfragment (); Call the Show Method pop-up dialog///The first parameter is Fragmentmanager object//The second is the label Datepickerfragment.show for the fragment that calls the method (Getfra
Gmentmanager (), "Date_picker");
}
}); ///Implement Datacallback GetData method @Override public void GetData (String data) {//data is the date time that the function is called back to fragment Tim
Etext.settext (data); }
}
Because the TimePickerFragment
dialog box is DatePickerFragment
started in the class, so write only date and time to choose, if you want to select a separate date or time, only need to rewrite onTimeSet()
or onDateSet()
method can be
Compatibility issues
Different versions of the Android version show different effects, android6.0 good, but in some low version of Android (such as 4.0, I do not have each version of the test) will be called two times back function, resulting in two time selection. There are a number of solutions, as long as the logic inside the callback function can be executed only once. A more general approach is provided here.
TimePickerDialog
DatePickerDialog
methods of rewriting onStop()
and
Overriding methods that are used directly in activity
Final Timepickerdialog Timepickerdialog = new Timepickerdialog (Testactivity.this, new Timepickerdialog.ontimesetlistener () {//The callback function is invoked after the time of the selection @Override public void Ontimeset (Timepicker view,
int hourofday, int minute) {Time.append ("" + Hourofday + ":" + minute);
Set TextView to display the time Timetext.settext the final selection;
}, hour, minute, true) {//overriding onStop () @Override protected void OnStop () {}}; Instantiate the Datepickerdialog object Datepickerdialog datepickerdialog = new Datepickerdialog (testactivity.this, New DatePickerDia Log. Ondatesetlistener () {//The callback function is invoked after the date is selected @Override public void Ondateset (DatePicker view, int years, int mo nthofyear, int dayofmonth) {//Because monthofyear will be less than the actual month January so this is going to add 1 time.append (year + "-" + (monthofyear+1) + "-
"+ DayOfMonth);
Select the time after the Date pop-up selection dialog box Timepickerdialog.show (); }, year, month, day {//rewrite OnStop @Override proteCTED void OnStop () {}};
The above wording will look messy, or you can create a new class to inherit TimePickerDialog
or DatePickerDialog
then override the onStop()
method
By FragmentDialog
using the override method
Just rewrite in the onCreateDialog()
method, the following code will be more clear
Return to New Datepickerdialog (Getactivity (), this, year, month, day) {
//rewrite onstop
@Override
protected void OnStop () {
}
};
Return to New Timepickerdialog (Getactivity (), this, hour, minute, true) {
//rewrite onstop
@Override
protected void OnStop () {
}
};
Summarize
The author is limited in level, but to ensure that the above code is personally realized over again. If there are any deficiencies are welcome to point out that this is the entire content of this article, I hope that the development of Android can help.