for first time i found the code to show datetimepicker in android (showing year, and month only), but i really confuse how to show only year in my datetime picker, can anyone help me? cause i'm newbie in programming
package com.example.datepicker;
import java.lang.reflect.Field;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
public class MainActivity extends Activity {
static final int DATE_DIALOG_ID = 1;
private int mYear;
private int mMonth;
private int mDay;
private EditText etPickADate;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etPickADate = (EditText) findViewById(R.id.et_datePicker);
etPickADate.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
showDialog(DATE_DIALOG_ID);
}
});
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
}
DatePickerDialog.OnDateSetListener mDateSetListner = new OnDateSetListener()
{
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth)
{
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDate();
}
};
#Override
protected Dialog onCreateDialog(int id)
{
switch (id)
{
case DATE_DIALOG_ID:
/*
* return new DatePickerDialog(this, mDateSetListner, mYear, mMonth,
* mDay);
*/
DatePickerDialog datePickerDialog = this.customDatePicker();
return datePickerDialog;
}
return null;
}
protected void updateDate() {
int localMonth = (mMonth + 1);
String monthString = localMonth < 10 ? "0" + localMonth : Integer
.toString(localMonth);
String localYear = Integer.toString(mYear).substring(2);
etPickADate.setText(new StringBuilder()
// Month is 0 based so add 1
.append(monthString).append("/").append(localYear).append(" "));
showDialog(DATE_DIALOG_ID);
}
private DatePickerDialog customDatePicker()
{
DatePickerDialog dpd = new DatePickerDialog(this, mDateSetListner, mYear, mMonth, mDay);
try {
Field[] datePickerDialogFields = dpd.getClass().getDeclaredFields();
for (Field datePickerDialogField : datePickerDialogFields)
{
if (datePickerDialogField.getName().equals("mDatePicker"))
{
datePickerDialogField.setAccessible(true);
DatePicker datePicker = (DatePicker) datePickerDialogField.get(dpd);
Field datePickerFields[] = datePickerDialogField.getType().getDeclaredFields();
for (Field datePickerField : datePickerFields)
{
if ("mDayPicker".equals(datePickerField.getName())||"mDaySpinner".equals(datePickerField
.getName()))
{
datePickerField.setAccessible(true);
Object dayPicker = new Object();
dayPicker = datePickerField.get(datePicker);
((View) dayPicker).setVisibility(View.GONE);
}
}
}
}
}
catch (Exception ex)
{}
return dpd;
}
}
and Thank u who can help me :D
To show only year in DatePickerDialog you also need to set Visibility GONE for Month NumberPicker using reflection. do it as:
if ("mDayPicker".equals(datePickerField.getName())
||"mDaySpinner".equals(datePickerField.getName()))
{
datePickerField.setAccessible(true);
Object dayPicker = new Object();
dayPicker = datePickerField.get(datePicker);
((View) dayPicker).setVisibility(View.GONE);
}else if("mMonthPicker".equals(datePickerField.getName())){
// to hide month picker
datePickerField.setAccessible(true);
Object monthPicker = new Object();
monthPicker = datePickerField.get(datePicker);
((View) monthPicker).setVisibility(View.GONE);
}
Related
I have to show calender using DatePickerDialog.
The below code is used:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TextView;
import android.widget.Toast;
public class DatePickerExample extends Activity {
private TextView Output;
private Button changeDate;
private Boolean mEnableNativeCalGridView = null;
String timeZone;
public static TimeZone tz;
private int year;
private int month;
DatePickerDialog d;
public Calendar c;
SimpleDateFormat sdf;
private int day;
public static IntentFilter s_intentFilter;
static final int DATE_PICKER_ID = 1111;
static{
s_intentFilter = new IntentFilter();
s_intentFilter.addAction(Intent.ACTION_TIME_TICK);
s_intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
s_intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
registerReceiver(m_timeChangedReceiver, s_intentFilter);
Output = (TextView) findViewById(R.id.Output);
changeDate = (Button) findViewById(R.id.changeDate);
// sdf = new SimpleDateFormat("EEE, MMM d, ''yy");//Wed, Jul 4, '01
// Show current date
Output.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" "));
// Button listener to show date picker dialog
changeDate.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
// On button click show datepicker dialog
showDialog(DATE_PICKER_ID);
}
});
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DATE_PICKER_ID:
((DatePickerDialog) dialog).updateDate(
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_PICKER_ID:
// open datepicker dialog.
// set date picker for current date
// add pickerListener listner to date picker
sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
tz = TimeZone.getDefault();
System.out.println("TimeZone "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezon id :: " +tz.getID());
timeZone = tz.getDisplayName(false, TimeZone.SHORT);
c= Calendar.getInstance();
c.setTimeZone(tz);
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
d = new DatePickerDialog(DatePickerExample.this, pickerListener, year, month,day);
setMinMaxdate();
return d;
}
return null;
}
////////////////////Fix for issue on OS 5.1 //////////////////////
public long getDateFormatted(String date){
String givenDateString = date;
long timeInMilliseconds = 0;
try {
Date mDate = sdf.parse(givenDateString);
timeInMilliseconds = mDate.getTime();
System.out.println("Date in milli :: " + timeInMilliseconds);
} catch (ParseException e) {
e.printStackTrace();
}
return timeInMilliseconds;
}
//////////////////////////////////////////
private DatePicker.OnDateChangedListener newchange= new OnDateChangedListener(){
#Override
public void onDateChanged(DatePicker view,
int year, int monthOfYear,int dayOfMonth) {
Toast.makeText(getApplicationContext(),
"onDateChanged", Toast.LENGTH_SHORT).show();
}};
DatePicker datePicker;
public void setMinMaxdate() {
//Time zone calculation
//TimeZone.setDefault(tz);
///////////////////////
long calEvtEndDate= getDateFormatted("Sun May 31 23:59:59 "+timeZone+" 2015");//System.currentTimeMillis();
long calEvtStartDate= getDateFormatted("Wed May 13 00:00:00 "+timeZone+" 2015");//System.currentTimeMillis()/2;
// long calEvtEndDate = getDateFormatted("Sun, may 31, '15");
//long calEvtStartDate = getDateFormatted("Wed, may 13, '15");
if(d != null){
datePicker = d.getDatePicker();
if(mEnableNativeCalGridView != null){
datePicker.setCalendarViewShown(mEnableNativeCalGridView.booleanValue());
}
// If Start Date is Greater than End Date then we are showing from valid StartDate
// value and we are not setting the maxdate.
if (calEvtStartDate > calEvtEndDate) {
datePicker.setMinDate(calEvtStartDate);
} else {
if (calEvtStartDate > 0) { // If Only ValidStart date is provided, then setting the minDate.
datePicker.setMinDate(calEvtStartDate);
}
if (calEvtEndDate > 0) { // If Only ValidEnd date is provided, then setting the maxDate.
datePicker.setMaxDate(calEvtEndDate);
}
}
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
System.out.println("-------resumed");
}
public DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
#Override
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
//view.updateDate(year, month, day);
System.out.println("---------------datesetchange");
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// Show selected date
Output.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
}
};
public void onDestroy() {
super.onDestroy();
unregisterReceiver(m_timeChangedReceiver);
}
private final BroadcastReceiver m_timeChangedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(Intent.ACTION_TIME_CHANGED) ||
action.equals(Intent.ACTION_TIMEZONE_CHANGED))
{
System.out.println("timezone changed---"+action.toString());
tz = TimeZone.getDefault();
System.out.println("TimeZone "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezon id :: " +tz.getID());
timeZone = tz.getDisplayName(false, TimeZone.SHORT);
// Intent intent1 = getIntent();
// finish();
// startActivity(intent1);
showDialog(DATE_PICKER_ID);
}
}
};
}
When the app is running, I go to the settings and change the Timezone to such a value so that the current date will change. Now when we select any date in the dialog, it behaves abnormally and goes to other date. I have used setMinDate() and setMaxDate() methods. This happens only in Android OS 5.1.
Any idea or help? Thanks in advance.
i have successfully implemented datepicker in android my problem is i want to disable all dates in datepicker prior to 1 st dec 2014 how can that be done ,i tried looking for examples but they all provide examples to disable date prior to todays date
i have not implemented any code for disabling previous dates any working example would be good
thanks in advance
here is my code
import java.util.Calendar;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
/** Private members of the class */
private TextView pDisplayDate;
private Button pPickDate;
private int pYear;
private int pMonth;
private int pDay;
/** This integer will uniquely define the dialog to be used for displaying date picker.*/
static final int DATE_DIALOG_ID = 0;
/** Callback received when the user "picks" a date in the dialog */
private DatePickerDialog.OnDateSetListener pDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
pYear = year;
pMonth = monthOfYear + 1;
pDay = dayOfMonth;
// if (pMonth<10)
// pMonth='0'+pMonth;
// if (pDay<10)
// pDay='0'+pDay;
updateDisplay();
displayToast();
}
};
/** Updates the date in the Te
* xtView */
private void updateDisplay() {
String formattedMonth = "" + pMonth;
String formattedDayOfMonth = "" + pDay;
if(pMonth < 10){
formattedMonth = "0" + pMonth;
}
if(pDay < 10){
formattedDayOfMonth = "0" + pDay;
}
// searchText.setText(formattedDayOfMonth + "/" + formattedMonth + "/" + year);
pDisplayDate.setText(
new StringBuilder()
// // Month is 0 based so add 1
.append(pYear).append("-")
.append(formattedMonth).append("-")
.append(formattedDayOfMonth).append(" "));
}
/** Displays a notification when the date is updated */
private void displayToast() {
Toast.makeText(this, new StringBuilder().append("Date choosen is ").append(pDisplayDate.getText()), Toast.LENGTH_SHORT).show();
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** Capture our View elements */
pDisplayDate = (TextView) findViewById(R.id.displayDate);
pPickDate = (Button) findViewById(R.id.pickDate);
/** Listener for click event of the button */
pPickDate.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
/** Get the current date */
final Calendar cal = Calendar.getInstance();
pYear = cal.get(Calendar.YEAR);
pMonth = cal.get(Calendar.MONTH);
pDay = cal.get(Calendar.DAY_OF_MONTH);
/** Display the current date in the TextView */
updateDisplay();
}
/** Create a new dialog for date picker */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
pDateSetListener,
pYear, pMonth, pDay);
}
return null;
}
}
set Max date like this :
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
DatePickerDialog dialog = new DatePickerDialog(mContext,
datePickerListener, myCalendar.get(Calendar.YEAR),
myCalendar.get(Calendar.MONTH), myCalendar
.get(Calendar.DAY_OF_MONTH));
dialog.getDatePicker().setMaxDate(new Date().getTime());
dialog.show();
}
return null;
}
done it might be helpful for someone can play with the if conditions accordingly
package com.example.datepicker;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView tvDisplayDate;
private Button btnChangeDate;
private int myear;
private int mmonth;
private int mday;
private int maxyear;
private int maxmonth;
private int maxday;
static final int DATE_DIALOG_ID = 999;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setCurrentDateOnView();
addListenerOnButton();
}
// display current date
public void setCurrentDateOnView() {
tvDisplayDate = (TextView) findViewById(R.id.tvDate);
final Calendar c = Calendar.getInstance();
maxyear = c.get(Calendar.YEAR);
maxmonth = c.get(Calendar.MONTH);
maxday = c.get(Calendar.DAY_OF_MONTH);
myear = 2014;
mmonth = 12;
mday = 31;
String formattedMonth = "" + mmonth;
String formattedDayOfMonth = "" + mday;
// set selected date into textview
if(maxmonth < 10){
formattedMonth = "" + maxmonth + 1;
}
if(maxday < 10){
formattedDayOfMonth = "0" + maxday;
}
// set current date into textview
tvDisplayDate.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(formattedMonth).append("-").append(formattedDayOfMonth).append("-")
.append(maxyear).append(" "));
}
public void addListenerOnButton() {
btnChangeDate = (Button) findViewById(R.id.btnChangeDate);
btnChangeDate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
// set date picker as current date
DatePickerDialog _date = new DatePickerDialog(this, datePickerListener, maxyear,maxmonth,
maxday){
#Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
if (year < 2014)
view.updateDate(2014, mmonth, mday);
if (monthOfYear < 12 && year == 2014)
view.updateDate(2014, 12, mday);
if (dayOfMonth < 31 && year == 2014 && monthOfYear == 12)
view.updateDate(2014, 12, 31);
if (year > maxyear)
view.updateDate(maxyear, maxmonth, maxday);
if (monthOfYear > maxmonth && year == maxyear)
view.updateDate(maxyear, maxmonth, maxday);
if (dayOfMonth > maxday && year == maxyear && monthOfYear == maxmonth)
view.updateDate(maxyear, maxmonth, maxday);
}
};
return _date;
}
return null;
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
myear = selectedYear;
mmonth = selectedMonth;
mday = selectedDay;
String formattedMonth = "" + mmonth;
String formattedDayOfMonth = "" + mday;
// set selected date into textview
if(mmonth < 10){
formattedMonth = "" + mmonth + 1;
}
if(mday < 10){
formattedDayOfMonth = "0" + mday;
}
tvDisplayDate.setText(new StringBuilder().append(formattedMonth)
.append("-").append(formattedDayOfMonth).append("-").append(myear)
.append(" "));
}
};
}
I am trying to disable date picker for future date but getting not idea...
Here is the what I have tried:
bday.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Calendar mcurrentDate=Calendar.getInstance();
year=mcurrentDate.get(Calendar.YEAR);
month=mcurrentDate.get(Calendar.MONTH);
day=mcurrentDate.get(Calendar.DAY_OF_MONTH);
DatePickerDialog mDatePicker =new DatePickerDialog(CreateAccountActivity.this, new OnDateSetListener()
{
#Override
public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday)
{
year = selectedyear;
month = selectedmonth;
day = selectedday;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
String currenttime = new String(dateFormat.format(cal.getTime()));
String selectedtime = new String (new StringBuilder().append(year).append("-").append(month+1).append("-").append(day));
String futuretime = new String (dateFormat.format(System.currentTimeMillis()));
if(selectedtime==currenttime)
{
Toast.makeText(getApplicationContext(), "you were not born in the future", Toast.LENGTH_SHORT).show();
bday.setText("");
}
else
{
bday.setText(new StringBuilder().append(year).append("-").append(month+1).append("-").append(day));
}}
},year, month, day);
mDatePicker.setTitle("Please select date");
mDatePicker.show();
}
});
Stackoverflow suggested to use:
mDatePicker.getDatePicker().setMaxDate(System.currentTimeMillis());
but in above condition how should I use this.?
I am trying to disable future date. But not getting any idea :(
After Declaring Listener on DatePicker use the mDatePicker.getDatePicker().setMaxDate(System.currentTimeMillis());
package com.keshav.datePicker_With_Hide_Future_Past_Date;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
EditText ed_date;
int year;
int month;
int day;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed_date=(EditText) findViewById(R.id.et_date);
ed_date.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Calendar mcurrentDate=Calendar.getInstance();
year=mcurrentDate.get(Calendar.YEAR);
month=mcurrentDate.get(Calendar.MONTH);
day=mcurrentDate.get(Calendar.DAY_OF_MONTH);
final DatePickerDialog mDatePicker =new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener()
{
#Override
public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday)
{
ed_date.setText(new StringBuilder().append(year).append("-").append(month+1).append("-").append(day));
int month_k=selectedmonth+1;
}
},year, month, day);
mDatePicker.setTitle("Please select date");
// TODO Hide Future Date Here
mDatePicker.getDatePicker().setMaxDate(System.currentTimeMillis());
// TODO Hide Past Date Here
// mDatePicker.getDatePicker().setMinDate(System.currentTimeMillis());
mDatePicker.show();
}
});
}
}
enter code hereI have used the DatePicker widget in android.Upon clicking that I want the datePickerdialog to show up and date should be set and the same I want to set to a textview.
Thanks in advance.
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dpd = new DatePickerDialog(this,new DatePickerDialog.OnDateSetListener() {
#Override
// TODO Auto-generated method stub
public void onDateSet(DatePicker view, int year,int monthOfYear, int dayOfMonth) {
startDateTextView.setVisibility(View.VISIBLE);
startDateTextView.setText(dayOfMonth + "-"+ (monthOfYear + 1) + "-" + year);
}
}, year, month, day);
dpd.show();
the above code i used,bt this works before i click on datepicker. please let me know how to use OnClickListener of datepicker to this
Try below code.
package com.example.datetimepicker;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
import java.text.DateFormat;
import java.util.Calendar;
public class MainActivity extends Activity {
Button date,time;
TextView preview;
int year,monthofyear,dayofmonth,hourofday,minute;
Calendar cal = Calendar.getInstance();
DateFormat dt = DateFormat.getInstance();
TimePickerDialog.OnTimeSetListener tpd;
DatePickerDialog.OnDateSetListener dpd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
date = (Button)findViewById(R.id.date);
date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new DatePickerDialog(MainActivity.this,dpd,
cal.get(Calendar.YEAR),cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH)).show();
}
});
time = (Button)findViewById(R.id.time);
time.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new TimePickerDialog(MainActivity.this,tpd,
cal.get(Calendar.HOUR_OF_DAY),cal.get(Calendar.MINUTE),
false).show();
}
});
preview = (TextView)findViewById(R.id.textView1);
dpd = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, monthOfYear);
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
preview.setText(new StringBuilder().append(year+"/")
.append(monthOfYear+"/").append(dayOfMonth));
}
};
tpd = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker arg0, int hourofday, int minute) {
// TODO Auto-generated method stub
cal.set(Calendar.HOUR_OF_DAY, hourofday);
cal.set(Calendar.MINUTE, minute);
preview.setText(new StringBuilder().append(hourofday+"/")
.append(minute));
}
};
}
}
you can use like this:
//variables
DatePicker dpResult;
static final int DATE_DIALOG_ID = 999;
//methods
public void setCurrentDateOnView() {
dpResult = (DatePicker) findViewById(R.id.dpResult);
dpResult.setVisibility(View.GONE );
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// set current date into datepicker
dpResult.init(year-7, month, day, null);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
// set date picker as current date
return new DatePickerDialog(this, datePickerListener, year, month,
day);
}
return null;
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// set selected date into textview
mbirthdayView.setText( (day)+(".")+(month + 1)+(".")+(year));
// set selected date into datepicker also
dpResult.init(year, month, day, null);
}
};
and finally you can call datepicker like this:
showDialog(DATE_DIALOG_ID);
Good day, can't seem to find a solution for this. i have 2 buttons that when pressed, opens a datepickerdialog, but my problem now is , how can i set them to the appropriate button on OnDateSet method. I am using a DialogFragment for the date and then implementing the DateListener in my activity. I have tried using getTag() but no success in getting the tag. here is what i tried:
public void showfromDatePickerDialog(View v) {
DialogFragment dateFragment = new DateDialogFragment();
dateFragment.show(getSupportFragmentManager(), "fromdatePicker");
}
public void showtoDatePickerDialog(View v) {
DialogFragment dateFragment = new DateDialogFragment();
dateFragment.show(getSupportFragmentManager(), "todatePicker");
}
public void onDateSet(DatePicker view, int year, int month, int day) {
StringBuilder builder = new StringBuilder();
builder.append(day).append("-")
.append(month).append("-")
.append(year);
String text= builder.toString();
if(view.getTag().toString().equals("fromdatePicker")) { // error here
Log.d(TAG, "got here" + text);
fromdate.setText(text);
}
if(view.getTag() == "todatePicker") {
todate.setText(text);
}
any ideas how to implement this? i keep seeing solutions about using 2 different DialogFragment class but am guessing there should be another way. or am i wrong? Thank you
ok, i have a work around for these. which can be helpful for anyone with this problem. if its slightly incorrect please let me know and i can change it. but this is what i did to solve this issue.
in on DateSet:
public void onDateSet(DatePicker view, int year, int month, int day) {
StringBuilder builder = new StringBuilder();
builder.append(day).append("-")
.append(month).append("-")
.append(year);
String text= builder.toString();
FragmentManager fragmanager = getSupportFragmentManager();
if(fragmanager.findFragmentByTag("fromdatePicker") != null) {
Log.d(TAG, "got here" + text);
fromdate.setText(text);
}
// if(view.getTag() == "todatePicker") {
if(fragmanager.findFragmentByTag("todatePicker") != null) {
todate.setText(text);
}
that way you can use the same dateListener for multiple calls and set the date appropriately based on the tag that was passed when calling show on the dialog.
Use below code of DatePicker Dialog.
private int mYear;
private int mMonth;
private int mDay;
Calendar cal4DatePicker = Calendar.getInstance();
Button btnDOB=findviewbyId(R.id.btndob);
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
cal4DatePicker.set(Calendar.YEAR, mYear);
cal4DatePicker.set(Calendar.MONTH, mMonth);
cal4DatePicker.set(Calendar.DAY_OF_MONTH, mDay);
btnDOB.setText(new StringBuilder()
.append(mDay).append("-").append(mMonth).append("-").append(mYear).append(" "));
}
};
on btnDOB you need to set click listner to show this DatePicker Dialog.
I have try same thing with Time Picker only. You can try out and set same for date picker also.
package com.example.toolboxtest;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
public class MainActivity extends FragmentActivity implements OnClickListener {
Button testBtn;
EditText testET;
static final int TIME_DIALOG_ID = 0;
int mHour = 0;
int mMinute = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testBtn = (Button) findViewById(R.id.testBTn);
testET = (EditText) findViewById(R.id.testET);
testBtn.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.testBTn:
showDialog(TIME_DIALOG_ID);
break;
}
}
private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour=hourOfDay;
mMinute = minute;
// myPrefs = ImportantDateReminderActivity.this.getSharedPreferences("myPrefs",MODE_WORLD_WRITEABLE);
// prefsEditor = myPrefs.edit();
// prefsEditor.putInt("hour", mHour);
// prefsEditor.putInt("minute", mMinute);
// prefsEditor.putString("a", a);
// prefsEditor.commit();
if(mHour==12){
//reminderSetTime.setText(new StringBuilder().append("12").append(":").append((minute)+" PM"));
testET.setText(mHour+":"+mMinute+" "+"PM");
}
else
updateTimeDisplay();
}
};
private void updateTimeDisplay() {
try {
Format formatter;
SimpleDateFormat df = new SimpleDateFormat("hh:mm");
Date d = df.parse(mHour + ":" + mMinute);
Calendar gc = new GregorianCalendar();
gc.setTime(d);
//gc.add(Calendar.HOUR, 0);
Date d2 = gc.getTime();
formatter = new SimpleDateFormat("hh:mm a");
String time = formatter.format(d2);
System.out.println("The TIME is: "+time);
testET.setText(time);
String hour = new SimpleDateFormat("hh").format(d2);
String minute = new SimpleDateFormat("mm").format(d2);
String a = new SimpleDateFormat("a").format(d2);
System.out.println("The Hour is: "+hour+ " "+minute+ " " +a);
/*myPrefs = this.getSharedPreferences("myPrefs",MODE_WORLD_WRITEABLE);
prefsEditor = myPrefs.edit();
prefsEditor.putInt("hour", Integer.parseInt(hour));
prefsEditor.putInt("minute", Integer.parseInt(minute));
prefsEditor.putString("a", a);
prefsEditor.putString("complateTime", time);
prefsEditor.commit();*/
//addTwoMonthNotification();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
return new TimePickerDialog(this,mTimeSetListener, mHour, mMinute, false);
}
return null;
}
}
Hope it will help you.
Please let me know if there is any issue.