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();
}
Related
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;
}
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 developing an app in Kotlin (if you don't know about kotlin I am sure you can still help with your Android/Java experience)
Details:
I have a Spinner in there my app.Though it is not responding to clicks once it pops up and even shows some weird views. And because of that the OnItemSelected listener is never fired either.
I start the method to update the spinner from an AsyncRealm call.
Here's the code:
This whole function runs, the spinner is not null, after attaching the listener, it is no longer null either (when debugging).
private fun updateCategorySpinner(result: MutableList<Category>) {
info("updateCategorySpinner")
val arrayAdapter: ArrayAdapter<String> = ArrayAdapter(ctx, R.layout.spinner_item, result.map{ it.category })
arrayAdapter.setDropDownViewResource(R.layout.spinner_item)
arrayAdapter.notifyDataSetChanged()
categorySpinner.adapter = arrayAdapter
info("updateCategorySpinner done")
}
result.map{..} creates a MutableList with Category names.
Problem:
I have no idea why there are those arrows, but no matter what layout I
use (even if just a simple TextView) they are there
What am I missing here?
Disabling the listener doesn't help.
Attaching the listener with Anko doesn't help.
The listener fires once when it is initialized, that's it.
Once the dropdown opens it is completely stuck.
I am creating my views with Anko.
The R.layout.spinner-item is just a <Textview>.
class AddTodoFragmentUi:AnkoComponent<ViewGroup>,AnkoLogger {
override fun createView(ui: AnkoContext<ViewGroup>): View {
val editTextTheme = R.style.Widget_AppCompat_EditText
return with(ui){
verticalLayout {
info("inVerticalLayout")
verticalPadding =dip(15)
gravity = Gravity.CENTER
editText(editTextTheme){
id = R.id.txt_todo_desc
hintResource = R.string.txt_todo_desc_hint
width = matchParent
}
spinner(R.style.Widget_AppCompat_Spinner){
id= R.id.spinner_todo_category
prompt = "Select a Category"
}
button{
id = R.id.btn_add_todo
textResource = R.string.btn_add_todo
width = matchParent
}
button{
id = R.id.btn_del_todo
textResource = R.string.btn_del_todo
width = matchParent
visibility = View.INVISIBLE
}
}.applyRecursively {view -> when(view){
is EditText -> view.textSize = 20f
is Button -> view.textSize = 30f
}
}
}
}
image:
Okay, so the issue of non-responsiveness was with setting up the Widget_app_compact spinner theme.
spinner(R.style.Widget_AppCompat_Spinner){
id= R.id.spinner_todo_category
prompt = "Select a Category"
Removing it solves the problem.
Don't lose two days as I did on this, please :D.
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());
I want to show an AlertDialog with one option that might change on every request. So for example at one time I want to show the option "add to contacts" while another time it should be "remove from contacts".
My code does work on the first time, however Android seems to cache the AlertDialog so that onCreateDialog is not executed next time. Therefore the option doesnt change anymore. Can I prevent this caching, or is there just another way of changing the option?
I am working with SDK 1.5 but using 1.1.
#Override
protected Dialog onCreateDialog(final int id) {
...
String add_remove_contact = res.getString(R.string.profile_add_to_contacts);
if (user.getContacts().contains(profileID)) {
add_remove_contact = res.getString(R.string.profile_remove_from_contacts);
// TODO: this string is not changed when contact status changes
}
final CharSequence[] items = {res.getString(R.string.view_profile),
res.getString(R.string.profile_send_message),
add_remove_contact};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
...
return builder.create();
}
Take a look at onPrepareDialog method that will be called before dialog is shown. There You can change the required values based on request type.
Example with date picker
#Override
protected Dialog onCreateDialog(final int id) {
switch (id) {
case DIALOG_DATE_ID:
final Calendar c = Calendar.getInstance();
return new DatePickerDialog(this, this, c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
default:
return super.onCreateDialog(id);
}
}
#Override
protected void onPrepareDialog(final int id, final Dialog dialog) {
switch (id) {
case DIALOG_DATE_ID:
//update to current time
final Calendar c = Calendar.getInstance();
((DatePickerDialog) dialog).updateDate(c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
break;
}
}
You can also use the removeDialog(int) function of the Activity. When a dialog is dismissed, the Activity basically stores the state of the dialog (for performance reasons I would imagine). Calling removeDialog(int) on the dialog forces the activity to unload all references for the dialog and dismisses it from the screen if it's being shown.
Creating Dialogs
Activity#removeDialog(int)
This is a dup of this question:
Android: Can not change the text appears in AlertDialog
You can also do it this way:
http://andmobidev.blogspot.com/2010/03/modifying-alert-dialogs-list-items.html
Does seem to slow down the display of the longpress menu though...
I think I have a fix for the inconsistent behavior mentioned above. When initially creating the dialog (when it's still an AlertDialog.Builder), you have to set the message to an initial state (not null) or onPrepareDialog will NOT overwrite it with the intended value. So when you're creating the dialog, do something like this to always have a non-null value in the message. I struggled with this for days and found this solution by accident:
AlertDialog.Builder resultAlert = new AlertDialog.Builder(context);
if ( message == null ) {
resultAlert.setMessage("");
} else {
resultAlert.setMessage(message);
}
When you have a custom dialog you can change custom items by using dialog.getWindow().findViewById(...)
This example save the last text shown and display it again the next time you show the dialog.
// custom dialog
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.customized);
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
EditText dialogText = (EditText)dialog.getWindow().findViewById(R.id.customText);
savedText = dialogText.getText();
}
});
dialog.show();
EditText dialogText = (EditText)dialog.getWindow().findViewById(R.id.customText);
dialogText.setText(savedText);
Customized dialog's xml:
<?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">
<Button
android:id="#+id/buttonOK"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="OK"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="16dp" />
<EditText
android:id="#+id/customText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="19dp"
android:hint="Message"
android:ems="10"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
I understand the performance reasons for using activity managed dialogs, but would recommend that they are not used except for simple cases. The reasons for this are:
The Bundle argument was only added in API Level 8, so can't be adopted for backwards compatibility. This effectively means that 'onPrepareDialog' needs to rely on non-local variables for state differences;
Practice indicates poor and inconsistent behaviour in response to any dialog changes made in the body of 'onPrepareDialog'.
None of these difficulties arise if Dialogs are subclassed and created as needed. 'setOwnerActivity' can be called if necessary.
And I got a idea but not so good.*This is used when the users don't use the dialog quite frequently!*The solution :first,you should declare a variable (int type) and make the default value as 0.such as private int i=0;
and before you use the showDialog methods of Activity,increase the int variable i and post the value i as the parameter as showDialog method.
the code may like this
private int i=0;
//before you show the dialog
this.i++;
this.showDialog(this.i);
exactly. for AlertDialog, that was created w/ Builder.create(), onPrepareDialog() is useless. Builder is one-way in that once the dialog is created, you can't update. i mean can't loosely, i am sure you could get a handle to the view and do it all manually, but that defeats the point of using the builder in the first place.
the only solution i found was to manually create / show / dismiss the dialog instead of using onCreateDialog(), showDialog(), etc. i tried calling removeDialog(), but that did not seem to work.