I'd like to have a date picker dialog with a "Today" button. If I click on Today button, it should reset datepicker to current date, without closing the dialog.
I have the following code:
Calendar today = Calendar.getInstance();
DatePickerDialog datePickerDialog = new DatePickerDialog(context, R.style.MyDialogStyle, date, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH));
datePickerDialog.setButton(DialogInterface.BUTTON_NEUTRAL, "Today", (dialog, which) -> {
datePickerDialog.updateDate(today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH));
});
datePickerDialog.show();
Expected behavior: set datepicker's date to current date without closing the dialog.
Actual behavior: dialog closes, date doesn't change.
I also tried with new DatePickerDialog(...), and
datePickerDialog.getDatePicker().init(today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH), null);
but it still doesn't work, only closes the dialog.
What am I missing here?
Is there a way to update datepicker's date programmatically without closing the dialog?
By default click button calls also dismiss() method to close the DatePickerDialog. It applies also to the DialogInterface.BUTTON_NEUTRAL button which you use for 'Today'.
Probably the simplest way to avoid this is to override the DatePickerDialog.dismiss() method and skip calling super.dismiss() if the 'Today' button was clicked.
Here is my working code in Kotlin I use for the same purpose (Today button for the DatePickerDialog). I use skipDismiss flag to know when to skip dismissal.
val datePickerDialog = object : DatePickerDialog(
this#MainActivity,
settings.currentTheme,
DatePickerDialog.OnDateSetListener { _, chosenYear, chosenMonth, dayOfMonth ->
calendar.set(Calendar.YEAR, chosenYear)
calendar.set(Calendar.MONTH, chosenMonth)
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
text_view_chosen_date.text = SimpleDateFormat("dd/MM/yyyy", Locale.US).format(calendar.time)
},
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH)
) {
override fun dismiss() {
if (!skipDismiss) {
super.dismiss()
} else {
skipDismiss = false
}
}
}
And of course the 'Today' button listener should set the skipDismiss flag to true when called. Here is my code for that:
datePickerDialog.setButton(DialogInterface.BUTTON_NEUTRAL, "Today") { dialog, which ->
val today = Calendar.getInstance()
(dialog as DatePickerDialog).updateDate(
today.get(Calendar.YEAR),
today.get(Calendar.MONTH),
today.get(Calendar.DAY_OF_MONTH)
)
skipDismiss = true;
}
Related
I am currently working on a school project, and in the school project, I need to add a DatePickerDialog in the register page to allow the user to pick their birth date.
I wanted to add a .setMaxDate() property to only allow users above a certain age to sign up for the app. When I added the .setMaxDate() property, the DatePickerDialog stopped showing the picked date as intended.
Here's my code to give you some context:
//[Inside of onCreate()]
final Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 16-calendar.get(Calendar.YEAR));
datePickerDialog = new DatePickerDialog(this, dateSetListener, Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH);
datePickerDialog.getDatePicker().setMaxDate(calendar.getTimeInMillis());
//[Inside of onCreate()] OnClick to show dialog
datePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
datePickerDialog.show();
}
});
//[Outside of onCreate()]
public DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
age = new Date(year-1900, month, day);
datePicker.setText(sdf.format(age));
calendarError.setError(null);
}
};
It's important to note that the DatePickerDialog works just fine without this line:
datePickerDialog.getDatePicker().setMaxDate(calendar.getTimeInMillis());
, but setting a max date is a necessity. This is what the DatePickerDialog shows instead of what's intended:
As you can see, the date shown as picked and the actual date selected by the user and saved in a Date object later are different. It's worth noting that I can't show this in a screenshot, but choosing a different year by clicking the top row and changing a year, or clicking on a different date snaps the DatePickerDialog to the current date but 16 years ago, yet it still saves them as the selected date by clicking the OK option.
I need to change default text values on timepicker in android (java) and can't figure out how to do that.
I've found .setTitle and .setmessage, but when clicking on keyborad icon in Timepicker dialog:
and shows another way to change time it has another title and default message as instructions that I would like to change Second timepicker dialog output
.
I'm calling a simple TimePickerDialog. Any suggestions? regards
You can check this out. This works for me good.
#Subscribe
public void setAlarm(OnAlarmClickEvent event) {
arrivalTime = event.arrivalTime;
alarmTime = event.arrivalTime;
int reminder = Integer.parseInt(sharedPreferences.getString(getString(R.string.pref_key_alarm_reminder), "5"));
alarmTime = alarmTime.minusMinutes(reminder);
TimePickerDialog timePickerDialog = new TimePickerDialog(
this,
this,
alarmTime.getHourOfDay(),
alarmTime.getMinuteOfHour(),
DateFormat.is24HourFormat(this)
);
timePickerDialog.setTitle(R.string.alarm_dialog_title);
timePickerDialog.setMessage(getString(R.string.alarm_dialog_message_fmt, DateUtils.formatTime(arrivalTime)));
timePickerDialog.show();
}
thanks for checking by. So I've been working on a project which ill expand/add some features to it eventually and currently im working on requesting permissions with Dexter (https://github.com/Karumi/Dexter). I've been able to get it working and when the user clicks on the Add Picture button it also asks the user for permissions, but I've encountered an issue I can't seem to solve myself. So the issue is if the user opens the app for the first time and clicks on the "Add Image" button and then chooses User clicks on add picture button and chooses first option
And lets assume the user denies all permissions, if the user clicks on the button again the app asks for the permissions again but this time with the "deny and dont ask again" option. And I've built a small Dialog that pops up that explains why the permissions are needed and can lead the user to the settings. But I've found out that if the user actually allows the permissions on the second go the app still pops that window and I just wasn't able to solve it.
User allows permissions
Msg still pops even though user gave permissions
Here is my code:
// Creating the variables of Calender Instance and DatePickerDialog listener to use it for date selection
// A variable to get an instance calendar using the default time zone and locale.
private var cal = Calendar.getInstance()
/* A variable for DatePickerDialog OnDateSetListener.
* The listener used to indicate the user has finished selecting a date. It will be initialized later. */
private lateinit var dateSetListener: DatePickerDialog.OnDateSetListener
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_happy_place)
// Adds the back button on the ActionBar
setSupportActionBar(toolbar_add_place)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
toolbar_add_place.setNavigationOnClickListener {
onBackPressed()
}
// Initialize the DatePicker and sets the selected date
// https://www.tutorialkart.com/kotlin-android/android-datepicker-kotlin-example/
dateSetListener = DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->
cal.set(Calendar.YEAR, year)
cal.set(Calendar.MONTH, month)
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)
updateDateInView()
}
// Uses functionality in the onClick function below
et_date.setOnClickListener(this)
tv_add_image.setOnClickListener(this)
}
// This is a override method after extending the onclick listener interface (gets created automatically)
override fun onClick(v: View?) {
when (v!!.id) {
R.id.et_date -> {
DatePickerDialog(
this#AddHappyPlaceActivity, dateSetListener,
cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)
).show()
}
R.id.tv_add_image -> {
val pictureDialog = AlertDialog.Builder(this)
pictureDialog.setTitle("Select Action")
val pictureDialogItems =
arrayOf("Select photo from gallery", "Capture photo from camera")
pictureDialog.setItems(pictureDialogItems) { _, which ->
when (which) {
0 -> choosePhotoFromGallery()
1 -> Toast.makeText(
this,
"Camera selection coming soon",
Toast.LENGTH_SHORT
).show()
}
}
pictureDialog.show()
}
}
}
// Method used for image selection from GALLERY/PHOTOS
private fun choosePhotoFromGallery() {
// Asking for permissions using DEXTER Library
Dexter.withContext(this).withPermissions(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA
).withListener(object : MultiplePermissionsListener {
override fun onPermissionsChecked(report: MultiplePermissionsReport?) {
// Here after all the permission are granted, launch the gallery to select and image.
if (report!!.areAllPermissionsGranted()) {
Toast.makeText(
this#AddHappyPlaceActivity,
"Storage READ/WRITE permission are granted. Now you can select an image from GALLERY or lets says phone storage.",
Toast.LENGTH_SHORT
).show()
}
}
override fun onPermissionRationaleShouldBeShown(
permissions: MutableList<PermissionRequest>?,
token: PermissionToken?
) {
token?.continuePermissionRequest()
showRationalDialogForPermissions()
}
}).onSameThread().check()
}
// Message to be shown if user denies access and possibly send him to the settings
private fun showRationalDialogForPermissions() {
AlertDialog.Builder(this).setMessage(
"It looks like you have turned off " +
"permissions required for this feature"
).setPositiveButton("GO TO SETTINGS")
{ _, _ ->
try {
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
val uri = Uri.fromParts("package", packageName, null)
intent.data = uri
startActivity(intent)
} catch (e: ActivityNotFoundException) {
e.printStackTrace()
}
}.setNegativeButton("Cancel") { dialog, _ ->
dialog.dismiss()
}.show()
}
// A function to update the selected date in the UI with selected format.
private fun updateDateInView() {
val myFormat = "dd.MM.yyyy"
val sdf = SimpleDateFormat(myFormat, Locale.getDefault())
et_date.setText(sdf.format(cal.time).toString())
}
}
As you can see im talking about the function "showRationalDialogForPermissions()" that gets initalized in the function "onPermissionRationaleShouldBeShown".
If someone knows how to solve this or has any tips that I could give a go I would really appreciate it.
Kind regards,
EDIT: Also I've realised if the user clicks "Deny and don't ask again" and cancels my Dialog, the app doesnt seem to make the Dialog appear after that. Pretty much nothing happens.
So I've tried a few things and I got it somehow working (there are still flaws)
I changed the following:
R.id.tv_add_image -> {
val pictureDialog = AlertDialog.Builder(this)
pictureDialog.setTitle("Select Action")
val pictureDialogItems = arrayOf("Select photo from gallery", "Capture photo from camera")
pictureDialog.setItems(pictureDialogItems) {
_, which ->
when(which) {
0 -> choosePhotoFromGallery()
1 -> Toast.makeText(this, "Camera selection coming soon", Toast.LENGTH_SHORT).show()
}
}
pictureDialog.show()
addButtonClicked += 1
if (addButtonClicked > 2) {
if (ContextCompat.checkSelfPermission(this#AddHappyPlaceActivity,
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
showRationalDialogForPermissions()
}
if (ContextCompat.checkSelfPermission(this#AddHappyPlaceActivity,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
showRationalDialogForPermissions()
}
if (ContextCompat.checkSelfPermission(this#AddHappyPlaceActivity,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
showRationalDialogForPermissions()
}
}
}
It's not an optimal solution but I just increment a value i created by 1 and once it reaches 3 (so assumed the user somehow managed to deny 2 times in a row) it pops that window up. Flaws would be that you somehow have to click the cancel button 2 times after giving permissions. But it somehow works and does what i was looking for; if someone has any different ideas, or ways to improve this "solution" it would be much appreciated
I'm using borax12 materialdaterangepicker and want to know how I can change the colours to customise the dialog calendar and also when the user selects a date change to the To tab?
Code:
// Show a datepicker when the dateButton is clicked
dateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
to = Calendar.getInstance();
DatePickerDialog dpd = com.borax12.materialdaterangepicker.date.DatePickerDialog.newInstance(
Tab2.this,
to.get(Calendar.YEAR),
to.get(Calendar.MONTH),
to.get(Calendar.DAY_OF_MONTH)
);
dpd.setAutoHighlight(mAutoHighlight);
dpd.show(getActivity().getFragmentManager(), "Datepickerdialog");
dpd.setYearRange(2016, 2017);
dpd.isThemeDark();
}
});
return v;
}
1). Change colours, background where the green is and maybe the tabs where the FROM and TO are and also the text. I can probably work all this out if I know how to start customising it.
2) When the user selects a day on the calender then switch to the To tab.
I am trying to build an android app and have come across a situation where I want a user to navigate between Dates by clicking Previous (Month) and Next (Month) buttons. I however do not want the user to go to a month after the current month. I would like the App to prompt a dialog letting the user know that they cant select a month after the current. Below is my code snippet - I am getting an error on two portions
01. if(formattedDate.before(currentMonth) || formattedDate.equals(currentMonth)){
On the above I am getting an error saying
The method before(Calendar) is undefined for the type String
02. new AlertDialog.Builder(HomeFragment.this)
and on the above I am getting an error saying
The constructor AlertDialog.Builder(HomeFragment) is undefined
Below is my full code for the on-click listener
NextPicker.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(formattedDate.before(currentMonth) || formattedDate.equals(currentMonth)){
c.add(Calendar.MONTH, 1);
formattedDate = df.format(c.getTime());
Log.v("NEXT DATE : ", formattedDate);
DatePicker.setText(formattedDate);
}
else{
new AlertDialog.Builder(HomeFragment.this)
.setTitle("Wrong Date Selection!")
.setMessage("The Month Selected must be before or equal to current month")
.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
}
}
});
Your first problem is that formattedDate is a String. It needs to be a java.util.Date.
Your second problem comes from the fact that the AlertDialog.Builder constructor requires a Context sub-class. Fragment is not a Context sub-class, but Activity is. Try something like
new AlertDialog.Builder(HomeFragment.this.getActivity());