How to Change the Datepicker style for Android - java

I'm currently making a registration form, and one of the fields is for the users Date of Birth. I want to use datepicker, however I don't want the calendar layout as shown below:
I want the layout to look something like this so that way its easier to choose the year and month without having to scroll through everything:
However I do not know how to go about this, or what to put inside the styles.xml file. Any help would be greatly appreciated.

Add this to style.xml
<style name="date_picker_theme" parent="#android:style/Widget.DatePicker">
And then you should apply style for your date picker like this:
<DatePicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/datePicker"
style="#style/date_picker_theme" />

Create style with
<style name="DatePicker" parent="#android:style/Theme.Holo.Light">
<item name="android:datePickerStyle">#android:style/Widget.DatePicker</item>
</style>
Then in custom fragment dialog xml
<DatePicker
android:theme="#style/DatePicker"
android:id="#+id/fragment_date_picker_control"
android:datePickerMode="spinner"
android:spinnersShown="true"
android:calendarViewShown="false"
android:layout_marginLeft="#dimen/margin_normal"
android:layout_marginRight="#dimen/margin_normal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
Link : http://yogeshkalwar.blogspot.in/2017/08/custom-spinner-datepicker-supporting-n70.html

To set the DatePicker style globally, add the following to style.xml, or adjust existing content:
<resources>
<style name="AppTheme" parent="#style/Theme.AppCompat.Light">
<item name="android:datePickerStyle">#style/MyDatePicker</item>
</style>
...
</resources>
And define your customized DatePicker style, either in style.xml or a separate file, e.g.:
<resources>
<style name="MyDatePicker" parent="#android:style/Widget.DatePicker">
<item name="android:calendarViewShown">false</item>
<item name="android:datePickerMode">spinner</item>
</style>
</resources>

It might be too late but you can set it programmatically like these.
Apply it inside your onClick listener.
DatePickerDialog datePicker = new DatePickerDialog(
this,
android.R.style.Theme_Holo_Light_Dialog_MinWidth,
datePickerListener,
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH));
datePicker.setCancelable(false);
datePicker.setTitle("Select the date");
datePicker.show();
The android.R.style.Theme_Holo_Light_Dialog_MinWidth create style that you want.
Hope it helps someone.

Above properties are of XML, if you want to set it programmatically you can you the below code but I haven't checked this code whether its working or not.
datepickerDialog_object.getDatePicker().setSpinnersShown(true);
datepickerDialog_object.getDatePicker().setCalendarViewShown(false);

DatePickerDialog has a convenience method, where you set the desired layout.
public DatePickerDialog(#NonNull Context context, #StyleRes int themeResId,
#Nullable OnDateSetListener listener, int year, int monthOfYear, int dayOfMonth) {
this(context, themeResId, listener, null, year, monthOfYear, dayOfMonth);
}
public static final int MODE_SPINNER = 1;
public static final int MODE_CALENDAR = 2;
Passing 1 or 2 in themesResId does the trick.

hi try this a simplest way...
public void datePicker(final Context context, final EditText editText, final String type) {
Calendar calendar = Calendar.getInstance();
final SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
DatePickerDialog datePickerDialog = new DatePickerDialog(context, R.style.DialogTheme, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(android.widget.DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
newDate.set(year, monthOfYear, dayOfMonth);
editText.setText(dateFormatter.format(newDate.getTime())
}
}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
// datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
datePickerDialog.show();
}
android in style.xml add below line
<style name="DialogTheme" parent="Theme.AppCompat.Light.Dialog">
<item name="colorAccent">#color/AppDarkBlue</item>
</style>

Related

Android Studio DatePickerDialog not showing picked date properly

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.

Update date in Android DatePickerDialog with Today button without closing dialog

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;
}

Alert Dialog in RecyclerView Adapter

I've implemented a long click listener to delete an entry from my recyclerview and I'd like to give the user one last chance to change their mind. I've done something similar in a 'standard' view using an Alert Dialog and i've made a few drawables for the buttons in the alert view that I would like to use again (to keep a constant interface among all my views)
The drawable I'm using is:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/minus_button"
android:state_pressed="false"
android:state_selected="false"/>
<item android:drawable="#drawable/add_button"
android:state_pressed="true"/>
</selector>
The alert I'm trying to use is :
public void deleteRequestCheck(final int tempIDval){
AlertDialog.Builder builder = new AlertDialog.Builder(this.context);
builder.setMessage("Are you sure you want to reset all your climbs back to zero?");
builder.setCancelable(false);
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
deleteEntry(tempIDval);
}
});
AlertDialog alert = builder.create();
alert.show();
Button nbutton = alert.getButton(DialogInterface.BUTTON_NEGATIVE);
nbutton.setBackgroundColor(getDrawable(R.drawable.button_tap));
nbutton.setTextColor(Color.WHITE);
Button pbutton = alert.getButton(DialogInterface.BUTTON_POSITIVE);
pbutton.setBackgroundColor(getDrawable(R.drawable.button_tap));
pbutton.setTextColor(Color.WHITE);
}
and I'm calling this from inside my Adapter class (where the longclick action is handled).
The issue I'm having is that
nbutton.setBackgroundColor(getDrawable(R.drawable.button_tap));
pbutton.setBackgroundColor(getDrawable(R.drawable.button_tap));
are giving me an error that it Cannot resolve method 'getDrawable(int)'. This has me stumped as this is identical to how I've created and called this alert dialog in my previous activities.
There are actually 2 ways you can do this:
1) Programmatically like:
nbutton.setBackground(ContextCompat.getDrawable(this.context‌​, R.drawable.mypositiveButtonDrawable));
But what if you want same button color for other dialogs? Why to duplicate the effort?
2) through styles.xml
Create a theme in your styles.xml like:
<style name="DiscardChangesDialog" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="buttonBarNegativeButtonStyle">#style/DialogButtonNegative</item>
<item name="buttonBarPositiveButtonStyle">#style/DialogButtonPositive</item>
</style>
<style name="DialogButtonNegative" parent="Widget.AppCompat.Button.Borderless">
<item name="android:textColor">#color/dialog_button_negative</item>
</style>
<style name="DialogButtonPositive" parent="Widget.AppCompat.Button.Borderless">
<item name="android:textColor">#color/dialog_button_positive</item>
</style>
and then use it like:
AlertDialog.Builder(this, R.style.DiscardChangesDialog)
and then you do not need to worry about adapter or anything.
Hope it helps!!!

Setting header colour in the new Material DatePicker

So am trying to change the colour of the header of my DatePicker. It doesn't appear to as easy as first though. You can do it in the XML like so:
android:headerBackground="#color/myColor" />
However there doesn't seem to be a way to be able to do this in code. The usual setters don't seem to be apparent (i.e datePicker.setHeaderBackground).
Any ideas?
Create custom datepicker dialog. See this link once.
You can use setAccentColor() for change color of header in this sample. use it like dpd.setAccentColor(Color.BLUE);.
If you don't want this color to buttons, just remove below lines from 'DatePickerDialog' class.
okButton.setTextColor(mAccentColor);
cancelButton.setTextColor(mAccentColor);
Here is the method to change header background of DatePickerDialog:
private void setDatePickerHeaderBackgroundColor(DatePickerDialog dpd, int color) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
Field mDatePickerField;
mDatePickerField = DatePickerDialog.class.getDeclaredField("mDatePicker");
mDatePickerField.setAccessible(true);
final DatePicker mDatePicker = (DatePicker) mDatePickerField.get(dpd);
int headerId = Resources.getSystem().getIdentifier("day_picker_selector_layout", "id", "android");
final View header = mDatePicker.findViewById(headerId);
header.setBackgroundColor(color);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
As you can see I'm using java reflection for Lollipop and above to get header view.
Usage:
DatePickerDialog dpd = new DatePickerDialog(this, this, 2016, 0, 11);
setDatePickerHeaderBackgroundColor(dpd, getResources().getColor(android.R.color.black));
dpd.show();
As a result we have:
EDIT:
In case you just want to set header background of DatePicker, that you've created in xml, forgot about java reflection, just use these lines to get it working:
DatePicker mDatePicker = (DatePicker) findViewById(R.id.date_picker);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
int headerId = Resources.getSystem().getIdentifier("day_picker_selector_layout", "id", "android");
final View header = mDatePicker.findViewById(headerId);
header.setBackgroundColor(getResources().getColor(android.R.color.black));
}
create this style :
<style name="MyDatePickerStyle" parent="#android:style/Widget.Material.Light.DatePicker">
<item name="android:headerBackground">#color/chosen_header_bg_color</item>
</style
and add this style to your dialog theme :
<style name="MyDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
<item name="android:datePickerStyle">#style/MyDatePickerStyle</item>
</style>
and add this dialog to your app theme :
<style name="MyDatePickerStyle" parent="#android:style/Widget.Material.Light.DatePicker">
<item name="android:headerBackground">#color/chosen_header_bg_color</item>
</style>
it is very wll explained here : Change Datepicker dialog color for Android 5.0
and this did work for me.
You need to override your DatePickerStyle, follow the steps,
1) Override DatePickerDialogTheme inside your app's base theme:
<style name="AppBaseTheme" parent="android:Theme.Material.Light">
....
<item name="android:datePickerDialogTheme">#style/CustomDatePickerDialogTheme</item>
</style>
2) Define CustomDatePickerDialogTheme
<style name="CustomDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
<item name="android:datePickerStyle">#style/CustomDatePickerStyle</item>
</style>
3) Overridden DatePickerStyle with the style CustomDatePickerStyle
<style name="CustomDatePickerStyle" parent="#android:style/Widget.Material.Light.DatePicker">
<item name="android:headerBackground">#color/header_bg_color</item>
</style>
Hope it helps.
Edit: Sorry for missing out the code part,
Use this style to create DatePickerDialog like this:
new DatePickerDialog(getActivity(),R.style.CustomDatePickerStyle, this, year, month, day);

Android time picker

I have used the code on this Android developers page to create a time picker when a button is pressed. However, I'm not getting the right look for it. I'm targeting my app to API 18 and the minimum is 10, because I want to support 2.3 due to the high usage. The minimum required SDK doesn't seem to have effect on the problem (I set it to 16):
I'm debugging the application on my HTC One S with Android 4.1.2, API 16. I get this kind of time picker but I want it to look modern, like in the Android developers page linked earlier.
http://www.b2creativedesigns.com/Tutorials/TimePicker/tutorial_timepicker2.png
Why does it use this prehistoric looking time picker?
I create the dialog using the following snippet. I call it from a FragmentActivity.
DialogFragment newFragment = TimePickerFragment.newInstance(2);
newFragment.show(getSupportFragmentManager(), "endtime");
This is the code for TimePickerFragment.
public static class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
private static int id;
public static TimePickerFragment newInstance(int _id) {
Bundle args = new Bundle();
args.putInt("id", _id);
id = _id;
TimePickerFragment f = new TimePickerFragment();
f.setArguments(args);
return f;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
id = getArguments().getInt("id");
int hour = start / 60; // start is a global variable, no problems in these
int minute = start % 60;
if(id == 2) {
hour = end / 60;
minute = end % 60;
}
return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
System.out.println(hourOfDay + ":" + minute);
setTime(id, hourOfDay, minute);
}
}
Use ContextThemeWrapper to explicitly provide your Holo-based theme for the Dialog, e.g.
return new TimePickerDialog(
new ContextThemeWrapper(getActivity(), R.style.YourAppStyleInheritingFromHolo),
this, hour, minute, DateFormat.is24HourFormat(getActivity()));
You need to use the Holo theme for the Holo widgets to work in your app. For example :
in your Manifest, under application :
android:theme="#style/AppTheme"
and in your res/values folder :
<style name="AppBaseTheme" parent="android:Theme.Light.NoTitleBar">
</style>
while using this in values-v11 and values-v14 :
<style name="AppBaseTheme" parent="android:Theme.Holo.Light.NoActionBar">
</style>
The system will switch between Theme.Light and Theme.Holo.Light depending on the Android version on the device.
You might want to take a look at this library. It is a backported TimePicker from Android 4.2 which works from android 2.1 upwards.
https://github.com/SimonVT/android-timepicker

Categories