Peut-on publier un exemple de code pour un simple sélecteur de date dans Android.
Si le sélecteur de date n'est pas possible dans Android, une option pour choisir une date est nécessaire.
Utilisez le DatePicker
http://developer.Android.com/reference/Android/widget/DatePicker.html
Il est disponible depuis l'API niveau 1
Voici un exemple d'utilisation du DatePickerDialog.
Ajoutez d'abord un TextView et un Button à votre layout.xml
<Button Android:id="@+id/myDatePickerButton"
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:text="Choose Date"/>
<TextView Android:id="@+id/showMyDate"
Android:layout_width="fill_parent"
Android:layout_height="wrap_content"/>
Ensuite, vous devez initialiser le Button et TextView dans la méthode onCreate de votre mise en page. Vous avez besoin de ces variables de classe
private int mYear;
private int mMonth;
private int mDay;
private TextView mDateDisplay;
private Button mPickDate;
static final int DATE_DIALOG_ID = 0;
Voici la méthode onCreate
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDateDisplay = (TextView) findViewById(R.id.showMyDate);
mPickDate = (Button) findViewById(R.id.myDatePickerButton);
mPickDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
// get the current date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
// display the current date
updateDisplay();
}
Méthode UpdateDisplay:
private void updateDisplay() {
this.mDateDisplay.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(mMonth + 1).append("-")
.append(mDay).append("-")
.append(mYear).append(" "));
}
L'écouteur de rappel pour le DatePickDialog
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDisplay();
}
};
La méthode onCreateDialog, appelée par showDialog ()
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
mDateSetListener,
mYear, mMonth, mDay);
}
return null;
}
J'espère que cela aide, l'a utilisé et cela fonctionne bien.
Exemple de
http://developer.Android.com/guide/tutorials/views/hello-datepicker.html
Voici une version mise à jour qui documente la rétrocompatibilité avec la bibliothèque de support:
http://developer.Android.com/guide/topics/ui/controls/pickers.html#DatePicker
public class dateresult extends Activity
{
private TextView tvdisplaydate;
private DatePicker dpResult;
private Button bntchangedate;
private int year;
private int month;
private int day;
static final int DATE_DIALOG_ID = 999;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
setCurrentdateonView();
addListenerOnButton();
}
public void setCurrentdateonView(){
tvdisplaydate = (TextView)findViewById(R.id.tvdate);
dpResult = (DatePicker) findViewById(R.id.dpResult);
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH) ;
day = c.get(Calendar.DAY_OF_MONTH);
tvdisplaydate.setText(new StringBuffer() .append(month+1).append("-").append(day).append("-").append(year).append(""));
dpResult.init(year, month, day, null);
}
public void addListenerOnButton(){
bntchangedate = (Button)findViewById(R.id.bntchangedate);
bntchangedate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(DATE_DIALOG_ID);
}
});
}
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
switch(id){
case DATE_DIALOG_ID:
return new DatePickerDialog(this,datePickerLisner,year,month,day);
}
return null;
}
private DatePickerDialog.OnDateSetListener datePickerLisner = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int Selectyear,int Selectmonth, int Selectday) {
year= Selectyear;
month= Selectmonth;
day = Selectday;
tvdisplaydate.setText(new StringBuilder()
.append(Selectmonth+1).append("-").append(Selectday).append("-").append(Selectyear).append(""));
dpResult.init(year, month, day, null);
}
};
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
Android:layout_width="match_parent"
Android:layout_height="match_parent"
Android:orientation="vertical" >
<Button
Android:id="@+id/bntchangedate"
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:text="Change Date" />
<TextView
Android:id="@+id/lbldate"
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:text="Current Date (M-D-YYYY) :"
Android:textAppearance="?android:attr/textAppearanceLarge"/>
<TextView
Android:id="@+id/tvdate"
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:text=""
Android:textAppearance="?android:attr/textAppearanceLarge" />
<DatePicker
Android:id="@+id/dpResult"
Android:layout_width="wrap_content"
Android:layout_height="wrap_content" />
</LinearLayout>
public class DatePickerDialogFragment extends DialogFragment{
//ResidenceActivity date = new ResidenceActivity();
Handler mHandler ;
int mDay;
int mMonth;
int mYear;
public DatePickerDialogFragment(Handler h){
/** Getting the reference to the message handler instantiated in MainActivity class */
mHandler = h;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
/** Creating a bundle object to pass currently set date to the fragment */
Bundle b = getArguments();
/** Getting the day of month from bundle */
mDay = b.getInt("set_day");
/** Getting the month of year from bundle */
mMonth = b.getInt("set_month");
/** Getting the year from bundle */
mYear = b.getInt("set_year");
/** DatePickerDialog's "Set" click listener */
DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener() {
// @Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mDay = dayOfMonth;
mMonth = monthOfYear;
mYear = year;
/** Creating a bundle object to pass currently set date to the fragment */
Bundle b = new Bundle();
/** Adding currently set day to bundle object */
b.putInt("set_day", mDay);
/** Adding currently set month to bundle object */
b.putInt("set_month", mMonth);
/** Adding currently set year to bundle object */
b.putInt("set_year", mYear);
/** Adding Current date in a string to bundle object */
b.putString("set_date", Integer.toString(mDay) + "/" + Integer.toString(mMonth+1) + "/" + Integer.toString(mYear));
/** Creating an instance of Message */
Message m = new Message();
/** Setting bundle object on the message object m */
m.setData(b);
/** Message m is sending using the message handler instantiated in MainActivity class */
mHandler.sendMessage(m);
}
};
/** Opening the DatePickerDialog window */
return new DatePickerDialog(getActivity(), listener, mYear, mMonth, mDay);
}
}
Step 1 : create a Java file:
package com.example.babs;
import Java.util.Calendar;
import Android.app.Activity;
import Android.app.DatePickerDialog;
import Android.app.Dialog;
import Android.app.DialogFragment;
import Android.os.Bundle;
import Android.view.View;
import Android.widget.DatePicker;
import Android.app.FragmentManager;
public class EditUserInfo extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_edit_view);
}
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
// pgrm mark ---- ---- ----- ---- ---- ----- ---- ---- ----- ---- ---- -----
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
}
}
public void showDatePickerDialog(View v) {
FragmentManager fragmentManager = getFragmentManager();
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(fragmentManager, "datePicker");
}
}// end main class EditUserInfo
step 2: your xml file must contain :
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:Android="http://schemas.Android.com/apk/res/Android"
Android:layout_width="match_parent"
Android:layout_height="match_parent"
Android:background="@Android:color/white"
Android:fillViewport="true" >
</ScrollView>
<Button
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:text="@string/pick_date"
Android:onClick="showDatePickerDialog" />
utiliser: import Java.util.Calendar;
à la place: importez Android.icu.util.Calendar.
ce package ne prend en charge que le niveau 24 d'API, pas moins que cela. Ceci est le package que nous devons utiliser pour obtenir l'agenda dans la boîte de dialogue,
cela fonctionne bien.
Pour utiliser DatePicker, ajoutez le code source ci-dessous dans votre OnCreate of Activity.
PS: assurez-vous que Android: focusable = "false" doit être fourni pour votre EditText.
// Edittext in your layout file
date = (EditText) findViewById(R.id.date);
// onclick on edit text
date.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog = new DatePickerDialog(MainActivity.this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
date.setText(dayOfMonth + "/"+ (monthOfYear + 1) + "/" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
Lorsque vous cliquez sur Edittext, le calendrier s'ouvre.
La réponse acceptée ne gère pas l'utilisateur qui clique sur Annuler dans le sélecteur de date. Dans ce cas, rien ne doit être mis à jour.
Je voulais la même chose que OP, mais je le voulais juste en ligne. Voici ce que j'ai utilisé:
Créez le rappel qui sera appelé lorsque le bouton OK du sélecteur de date est cliqué:
public void datePicked(int year, int month, int day) {
buttonDate.setText(String.valueOf(year) + "/" +
String.valueOf(month) + "/" + String.valueOf(day));
}
Utilisez ensuite le code suivant dans la méthode dans laquelle vous créez un bouton pour choisir la date:
buttonDate = (Button) rootView.findViewById(R.id.button_select_date);
buttonDate.setText("Select Date");
buttonDate.setOnClickListener(new View.OnClickListener() {
public void setReturnDate(int year, int month, int day) {
datePicked(year, month, day);
}
@Override
public void onClick(View v) {
Dialog datePickerDialog = new DatePickerDialog(activity, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
}
}, leagueEndDate.get(Calendar.YEAR), leagueEndDate.get(Calendar.MONTH), leagueEndDate
.get(Calendar.DAY_OF_MONTH));
datePickerDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
setReturnDate(((DatePickerDialog) dialog).getDatePicker().getYear(),
((DatePickerDialog) dialog).getDatePicker().getMonth(), ((DatePickerDialog) dialog)
.getDatePicker().getDayOfMonth());
}
});
datePickerDialog.show();
}
});