Development issue/problem:
I have a DatePickerDialog and I just want to see the month and the year. How can I change this code?
public null selectDatum2(View v) {
new DatePickerDialog(
act.this,
d1,
dateAndTime1.get(Calendar.YEAR) + 2,
dateAndTime1.get(Calendar.MONTH),
dateAndTime1.get(Calendar.MONTH),
dateAndTime1.get(Calendar.DAY_OF_MONTH)
).show();
}
private invalid updateLabel2() {
scadenza.setText(fmtDateAndTime.format(dateAndTime1.getTime());
}
datePickerDialog.OnDateSetListener d1=new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
dateAndTime1.set(Calendar.YEAR, year);
dateAndTime1.set(Calendar.MONTH, monthOfYear);
dateAndTime1.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel2();
} ;
Thank you very much.
How can I solve this problem?
Solution 1:
Try the following code. Only the DatePicker with year and month is displayed (no day).
private DatePickerDialog createDialogWithoutDateField() {DatePickerDialog dpd = new DatePickerDialog(this, null, 2014, 1, 24);try {java.lang.reflect.Field[] datePickerDialogFields = dpd.getClass().getDeclaredFields();for (java.lang.reflect.field datePickerDialogField: datePickerDialogFields) {als (datePickerDialogField.getName().equals(mDatePicker)) {datePickerDialogField.setAccessible(true);datePicker datePicker = (datePicker) datePickerDialogField.get(dpd);java.lang.reflect.Field[] datePickerFields = datePickerDialogField.getType().getDeclaredFields();for (java.lang.reflect.Field datePickerField: datePickerFields) {Log.i(test, datePickerField.getName());if (mDaySpinner.is equal to(datePickerField.getName()))) {datePickerField.setAccessible(where);Object dayPicker = datePickerField.get(datePicker);((View) dayPicker).setVisibility(View.GONE);}}}}} Catch(Exception – ex) {} return dpd;}.
This method displays a date selection dialog. So, in your onClick method, add the following code to display the dialog box.
createDialogWithoutDateField().show() ;
Solution 2:
When I recently encountered this problem myself, I tested different solutions for this and similar stack overflow problems.
Unfortunately I could not find a functional solution, especially for Android 5+.
Eventually I implemented my own simple DialogFragment with two NumberPickers. It must be compatible with all versions 3.0 and higher.
Here’s the code:
public class MonthYear PickerDialogue expands DialogFragment {
private static end int MAX_YEAR = 2099 ;
private DatePickerDialog.OnDateSetListener ;
public invalid setListener(DatePickerDialog.OnDateSetListener listener) {
this.listener = listener;
}
@Check public dialog
onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Receive inflatable layout
LayoutInflater inflater = getActivity().getLayoutInflater() ;
Calendar calendar = Calendar.getInstance() ;
Browse window = inflater.inflate(R.layout.date_picker_dialog, null) ;
final NumberPicker monthPicker = (NumberPicker) dialog.findViewById(R.id.picker_month) ;
final NumberPicker yearPicker = (NumberPicker) dialog.findViewById(R.id.picker_year) ;
monthPicker.setMinValue(0) ;
monthPicker.setMaxValue(11) ;
monthPicker.setValue(cal.get(Calendar.MONTH)) ;
int year = cal.get(Calendar.yEAR) ;
yearPiskeg.setMinValue(year) ;
yearPiskeg.setMaxValue(MAX_YEAR) ;
yearPiskeg.setValue(year) ;
builder.setView(dialog)// add action keys.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {@Overridepublic null onClick(DialogInterface dialog, int id) {listener.onDateSet(null, yearPicker.getValue(), monthPicker.getValue(), 0);}}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {public blank onClick(DialogInterface, int id) {MonthYearPickerDialog.This.getDialog().cancel();});gives builder.create();}})
And the layout
To show the use of the layout:
MonthYearPickerDialog pd = new MonthYearPickerDialog() ;
pd.setListener(this) ;
pd.show(getFragmentManager(), MonthYearPickerDialog) ;
Solution 3:
I do not recommend the use of Reflection for this kind of thing.
There’s an easier and nicer way:
((ViewGroup) datePickerDialog.getDatePicker()).findViewById(Resources.getSystem().getIdentifier(day, id, android))).setVisibility(View.GONE) ;
Note that the .getDatePickerDialog method works with API LEVEL >= 11.
Moreover, it does not work with PLC LEVEL >= 21.
Solution 4:
Stephan Klein Supplementary Preliminary Answer Form .
Since I’m obliged to make the year optional. And I also have the date of February 28th and the leap year.
Monthly/annual dialogues
public class MonthYear PickerDialogue expands DialogFragment {
Private Earpiece DatePickerDialog.onDateSetListener;
private int daysOfMonth = 31 ;
for the month; for the year; for the day;
Private calendar = Calendar.getInstance() ;
public total static string MONTH_KEY = monthValue ;
public total static string DAY_KEY = dayValue ;
public total static string YEAR_KEY = yearValue ;
int monthVal = -1 , dayVal = -1 , yearVal =-1 ;
Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState) ;
extraas = getArguments() ;
if(extraas != null){
monthVal = extraas.getInt(MONTH_KEY , -1) ;
dayVal = extraas.getInt(DAY_KEY , -1) ;
yearVal = extraas.getInt(YEAR_KEY , -1) ;
}
} } }.
public static MonthYearPickerDialog newInstance(int monthIndex , int daysIndex , int yearIndex) {
MonthYearPickerDialog f = new MonthYearPickerDialog() ;
// Enter the numbering of the power supply as an argument.
Bundle args = new Bundle();
args.putInt(MONTH_KEY, monthIndex);
args.putInt(DAY_KEY, daysIndex);
args.putInt(YEAR_KEY, yearIndex);
f.setArgumenten(args) ;
return f;
}
public invalid setListener(DatePickerDialog.OnDateSetListener listener) {
this.listener = listener;
}
@Check public dialog
onCreateDialog(Bundle savedInstanceState) {
//getDialog().setTitle(Add Birthday) ;
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()) ;
// Get inflatable layout
LayoutInflater inflater = getActivity().getLayoutInflater() ;
Viewer dialog = inflater.inflate(R.layout.month_year_picker, null);
monthPicker = (NumberPicker) dialog.findViewById(R.id.picker_month);
yearPicker = (NumberPicker) dialog.findViewById(R.id.picker_year);
dayPicker = (NumberPicker) dialog.findViewById(R.id.picker_day) ;
monthPicker.setMinValue(1) ;
monthPicker.setMaxValue(12) ;
if(monthVal != -1)// && (monthVal > 0 && monthVal 365;
}
}
And that’s what I call it.
Calendar = Calendar.getInstance() ;
if(etBirthday.getText().length()> 0 ){
if(checkIsYearAvailable(etBirthday.getText().toString().trim())))
Calendar = DateTimeOp.getCalendarFromFormat(etBirthday.getText().toString().trim(), Constants.dateFormat21) ;
other
Calendar = DateTimeOp.getCalendarFromFormat(etBirthday.getText().toString().trim() + , 1917,Constants.dateFormat21) ;
}
MonthyearPickerDialog pd = MonthyearPickerDialog.newInstance(calendar.get(Calendar.MONTH) + 1,
calendar.get(Calendar.DAY_OF_MONTH),calendar.get(Calendar.YEAR)) ;
pd.setListener(new DatePickerDialog.OnDateSetListener() {
@Override
public null and void onDateSet(View DatePicker, int selectedYear, int selectedMonth, int selectedDay) {
String formulatedDate = ;
if(selectedYear == 1904){Line currentDateFormat = selectedMonth + / + selectedDay;// + + selectedYear; //MM/dd/yyyyyformatedDate = DateTimeOp.oneFormatToAnother(currentDateFormat, Constants.dateFormat20, Constants.dateFormat24);};}else{Line currentDateFormat = selected Month + / + selectedDay + / + selectedYear; //MM/dd/yyyyyyyformatedDate = DateTimeOp.oneFormatToAnother(currentDateFormat, Constants.dateFormat0, Constants.dateFormat21);}.
andBirthday.setText (formatedDate);
}
});
pd.show(getFragmentManager(), MonthYearPickerDialog) ;
month_year_harvest.xml
Solution No 5:
Ksar E Ahmer’s answer is very easy to follow and in accordance with the request. I have used the same with the following changes, in accordance with my requirement.
- Kotlin conversion of the answer Xar E Ahmer .
- Added several error handling cases.
- No more equipment on 28/29. February is a leap year.
- For each year a checkbox to exclude the year (simplified for the user).
MonthyearPickerDialog.kt
Package com.example.*******
import android.app.AlertDialog
import android.app.DatePickerDialog
import android.app.dialog
import android.content.Context
import android.content.DialogInterface
import android.os.bundle
import android.util.Log
android.import
android.view.import
android.widget.CheckBox Import
android.widget.CompoundButton Import
android.widget.NumberPicker Import
android.app.DialogFragment
import java.util.Calendar.
Dialogue class month/year : DialogFragmentation() {
a personal headset for the dimmer: DatePickerDialog.OnDateSetListener = null
private var daysOfMonth = 31
The private var monthPicker: NumberPicker? = null
private var yearPicker : NumberPicker? = null
private var dayPicker : NumberPicker? = null
private var isEveryYearcheckBox : Tick? = zero.
fall cal private = Calendar.getInstance()
internal drive monthVal = -1
internal drive dayVal = -1
internal drive yearVal = -1
internal drive maxYearVal = -1
internal drive minYearVal = -1
override fun onAttach(context) {
super.onAttach(context)
}
fun override onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState))
val extraas = arguments
if (extraas != null) {
monthVal = extraas.getInt(MONTH_KEY, -1)
dayVal = extraas.getInt(DAY_KEY, -1)
yearVal = extraas.getInt(YEAR_KEY, -1)
maxYearVal = extraas.getInt(MAX_YEAR_KEY, -1)
minYearVal = extraas.getInt(MIN_YEAR_KEY, -1)
}
maxYearVal = if (maxYearVal == -1) 2025 else maxYearVal
minYearVal = if (minYearVal == -1) 1925 else minYearVal
If (minYearVal > maxYearVal) {
fall tempVal = maxYearVal
maxYearVal = minYearVal
minYearVal = tempVal
}
}
fun setListener(listener: DatePickerDialog.OnDateSetListener) {
this.listener = listener
}.
Overload the fun onCreateDialog (saveInstanceState: Bundle?): Dialogue {
fall builder = AlertDialog.Builder(activity)
// Get layout inflater
fall inflater = activity.layoutInflater
fall dialog = inflater.inflate(R.layout.month_year_picker, null)
monthPicker = dialog.findViewById(R.id.datepicker_month) as NumberPicker
yearPicker = dialog.findViewById(R.id.datepicker_year) as NumberPicker
dayPicker = dialog.findViewById(R.id.datepicker_day) as NumberPicker
isEveryYearcheckBox = dialog.findViewById(R.id.datepicker_isyearcheckBox) if CheckBox
isEveryYearcheckBox!! setOnCheckedChangeListener { compoundButton, b ->
if (b) {
yearPicker !!.isEnabled = false
yearPicker !!.value = minYearVal –
} otherwise {
yearPicker !!.isEnabled = true
if (yearVal !!)= -1 && yearVal != 1904)
yearVicer ! !.value = yearValue
else {
yearVoter ! !.value = cal.get(Calendar.YEAR)
}
}
if (monthPicker ! !.value == 2) {
daysOfMonth = 28
if (isLeapYear(yearPicker !!.value)) {
daysOfMonth = 29
}
dayPicker !!.maxValue = daysOfMonth
}
}
monthPicker!!!!.minValue = 1
monthPicker!!!!.maxValue = 12
if (monthValid != -1)
monthPicker !!!.value = monthValid
other
monthPicker !!!.value = cal.get(Calendar.MONTH) +1
monthPicker !!.displayValues = arrayOf(Jan, Feb, Mar, Apr, May, June, July, Aug, Sep, Oct, Nov, Dec)
dayPicker!!!.minValue = 1
dayPicker!!!.maxValue = days of the month
if (dayVal != -1)
dayPicker !!.value = dayValue
else
dayPicker !!.value = cal.get(Calendar.DAY_OF_MONTH)
Month Picker!!! SetOnValueChangedListener { picker, oldVal, newVal ->
when (newVal) {
1, 3, 5, 7, 8, 10, 12 -> {
daysOfMonth = 31
dayPicker!!!!maxValue = daysFromMonth
}
2 -> {
daysFromMonth = 28
if (isLapYear(yearPicker!!!! value)) {
daysFromMonth = 29
}
dayPicker!!!! maxValue = daysFromMonth
}
4, 6, 9, 11 -> {
daysMonth = 30
daysPicker!!.maxValue = daysMonth
}
}
}
fall maxYear = maxYearVal
fall minYear = minYearVal
fall arraySize = maxYear – minYear + 2
fall tempArray = arrayOfNulls(arraySize)
tempArray [0] = —
var tempYear = minusYear – 1
for (i in 0 to arraySize) {
if (i != 0) {
tempArray [i] = $tempYear
}
temperature year++
}
Log.i(, onCreateDialog : + tempArray.size)
yearPicker!!.minValue = minYear –
yearPicker!!.maxValue = maxYear
yearPicker!!!!.displayValues = tempArray
if (yearVal != -1 && yearValue != 1904) {
yearPicker !!.value = yearValue
} else {
isEveryYearcheckBox !!.isChecked = false
yearPicker !!!isEnabled = false
yearPicker !!.value = minusYear – 1
}
if (monthPicker !!.value == 2) {
daysOfMonth = 28
if (isLeapYear(yearPicker !!.value)) {
daysOfMonth = 29
}
dayPicker !!.maxValue = daysOfMonth
}
yearPicker !!.setOnValueChangedListener { picker, oldVal, newVal ->
try {
daysOfMonth = 28
if (isLeapYear(picker.value)). {
daysOfMonth = 29
}
dayPicker !!.maxValue = daysOfMonth
} catch (e: Exception) {
e.printStackTrace()
}
}.
builder.setView(dialogue)
// action keys
.setPositiveButton(R.string.ok) { dialogue, id ->
var year = yearPicker!!! value
as (year == minYear – 1) {
year = 1904
}
listener!!!!!! !.onDateSet(null, year, monthPicker !!.value, dayPicker !!.value)
}
.setNegativeButton(R.string.cancel) [dialog box, id -> [protected by email]()] }
Retourbouwer.create()
}
related object {
MONTH_KEY value = monthly value
DAY_KEY value = daily value
YEAR_KEY value = annual value
MAX_YEAR_KEY value = maximum annual value
MIN_YEAR_KEY value = minimum annual value
newFunnystance(monthIndex: B, Yearbook: B, MaxYearbook: B, MinYearbook: B) : Month / Year Dialogues {
fall f = MonthyearPickerDialog()
// Enter the service numbering as an argument.
val args = Bundle()
args.putInt(MONTH_KEY, monthIndex)
args.putInt(DAY_KEY, daysIndex)
args.putInt(YEAR_KEY, yearIndex)
args.putInt(MAX_YEAR_KEY, maxYearIndex)
args.putInt(MIN_YEAR_KEY, minYearIndex)
f.arguments= args
back f
}
Nice is the summer year (year: B) : Boolean {val cal = Calendar.getInstance()cal.set(Calendar.YEAR, year)return cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365}}}}
month_year_harvest.xml
Application example with different test cases in JAVA
Calendar calendar = Calendar.getInstance();
// Current date
MonthyearPickerDialog pd = MonthyearPickerDialog.Companion.newInstance(calendar.get(Calendar.MONTH) + 1,
calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.YEAR), -1, -1) ;
// SSTODO to test
// no year
//MonthYearPickerDialog pd = MonthYearPickerDialog.newInstance(calendar.get(Calendar.MONTH) + 1,
// calendar.get(Calendar.DAY_OF_MONTH), -1, -1) ;
// Minimum year 2020
// Month/Year monthDialoguePicker pd = Month/Year monthDialoguePicker.newInstance(calendar.get(Calendar.MONTH) + 1,
// calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.YEAR), -1, 2020) ;
// Maximum year 2018
// Month/YearDialoguePicker pd = Month/YearDialoguePicker.newInstance(calendar.get(Calendar.MONTH) + 1,
// calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.YEAR), 2018, -1) ;
// Maximum year 2019, minimum year 2019
// MonthyearPickerDialog pd = MonthyearPickerDialog.newInstance(calendar.get(Calendar.MONTH) + 1,
// calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.YEAR), 2019, 2019, 2019) ;
// maximum year 100, minimum year 5000
//MonthYearPickerDialog pd = MathYearPickerDialog.newInstance(calendar.get(Calendar.MONTH) + 1,
// calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.YEAR), 100, 5000)
// maximum year 100, minimum year 5000, year 99
//MonthYearPickerDialog pd = MonthYearPickerDialog.newInstance(calendar.get(Calendar.MONTH) + 1,
// calendar.get(Calendar.DAY_OF_MONTH), 99, 100, 5000) ;
pd.setListener(new DatePickerDialog.OnDateSetListener() {
@Override
public null and void onDateSet(View DatePicker, int selectedYear, int selectedMonth, int selectedDay) {
String formattedDate = ;
String currentDateFormat = ;
if(selectedYear == 1904) // no year
{
currentDateFormat = selectedMonth + / + selectedDay; //MM/dd
}
different {
currentDateFormat = selectedMonth + / + selectedDay + / + selectedYear; //MM/dd/yyyyy
}
Toast.makeText(MainActivityTestOne.this, SelectedDate ( MM/dd or. MM/dd/yyyyy ) : + currentDateFormat, Toast.LENGTH_LONG).show() ;
}
})) ;
pd.show(getFragmentManager(), STRING_DATE_PICKER ;)))
For users who need a date object as return value:-
we can create a date object from the return values of the day, month and year as follows (please correct any syntax errors)
SimpleDateFormat = new SimpleDateFormat(dd-MM-yyyyy) ;
currentDateString = selectedDay + – selectedMonth + – + selectedYear ;
long millis = format.parse(currentDateString).getTime() ;
Calendar = Calendar.getInstance() ;
calendar.setTimeInMillis( millis) ;
int date = calendar.get(CALENDAR.DATE) ;
Solution No 6:
It works very well for me:
DatePickerDialog monthDatePickerDialog = new DatePickerDialog(activity,
AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
@Override
public null and void onDateSet(type DatePicker, int year, int month, int day of the month) {
monthTextView.setText (year + / + (month + 1));
}
}, yearNow, monthNow, dayNow){
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getDatePicker().findViewById(getResources().getIdentifier(day,id,android)).setVisibility(View.GONE);
}
};
monthDatePickerDialog.setTitle(select_month);
monthDatePickerDialog.show() ;
Solution No 7:
It’s an old question, but now you can just use BetterPickers:
https://github.com/code-troopers/android-betterpickers
And use ExpirationPicker.
Hopefully this will solve the problem of some other lost souls who have searched everywhere in Google.
Solution No 8:
It works for me… Try this.
monthPicker.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Calendar mcurrentDate = Calendar.getInstance();
String myFormat = MMM yyyyy;
SimpleDateFormat sdf = new SimpleDateFormat (myFormat);
DatePickerDialog monthDatePickerDialog = new DatePickerDialog(getActivity(),
AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(View DatePicker, int year, int month, int dayOfmonth) {
mcurrentDate.set(Calendar.YEAR, year);
mcurrentDate.set(Calendar.MONTH, month);
monthPicker.setText(sdf.format(mcurrentDate).getTime());
mDay = dayOfMonth;
mMonth = month;
mYear = year;
}
}, mYear, mMonth, mDay){
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getDatePicker().findViewById(getResources().getIdentifier(day,id,android)).setVisibility(View.GONE);
}
};
monthDatePickerDialog.setTitle(Select month and year);
monthDatePickerDialog.show();
}
}.
Solution No 9:
Too late for the party. But if someone is looking for a version of Kotlin, I will rewrite Stephan Klein’s answer, change it to Kotlin, with a datalink style, month view and date input.
So, if you are looking for a constructor of MonthYearPickerDialog, you can create a class of MonthYearPickerDialog:
class MonthYearPickerDialog(expiry date : Date = Date()) : DialogFragmentation() {
party object {
private const val MAX_YEAR = 2099
}
Private Liaison with Latin Varnish : Dialogue MonthYearBinding
a personal headset for the dimmer: Are you listening to OnDateSet? = Fuck.
fun setListener(listener: OnDateSetListener?) {
this.listener = listener
}
Overload the fun onCreateDialog (saveInstanceState: Bundle?): Dialog {
binding = DialogMonthYearPickerBinding.inflate(requireActivity().layoutInflater)
fall cal : Calendar = Calendar.getInstance().apply { time = date }
binding.pickerMonth.run {
minValue = 0
maxValue = 11
value = cal.get(Calendar.MONTH)
displayValues = arrayOf(Jan,Feb,Mar,Apr,May,June,July,
Aug,Sep,Oct,Nov,Dec)
}
binding.pickerYear.run {
value year = cal.get(Calendar.YEAR)
minValue = year
maxValue = MAX_YEAR
value = year
}
Return AlertDialog.Builder(requireContext())
.setTitle(Select the Month View)
.setView(binding.root)
.setPositiveButton(Ok) { _, _ -> listener ?onDateSet(null, binding.pickerYear.value, binding.pickerMonth.value, 1) }
.setNegativeButton(Cancel) { _, _ -> dialog box ?.cancel() }
.create()
}
}
With his xml dialog_month_year_speaker :
To use it, call:
MonthYearPickerDialog(date).apply {
setListener { view, year, month, dayOfMonth ->
Toast.makeText(requireContext(), Set date: $year/$month/$dayOfMonth, Toast.LENGTH_LONG).show()
}
show(supportFragmentManager, MonthYearPickerDialog)
}
It would look like this:
CAUTION When used in fragment
Since Kotlin applies this keyword and MonthYearPickerDialog is also a fragment, make sure you call the appropriate FragmentManager in the show() method. Otherwise there may be a FATAL IllegalStateException: which is not related to the fragment processor.
If you z. B. you want to mention this in MyFragment, use @ to indicate that this is the case:
MonthYearPickerDialog(date).apply {
setListener { view, year, month, dayOfMonth ->
Toast.makeText(requireContext(), Set date: $year/$month/$dayOfMonth, Toast.LENGTH_LONG).show()
}
show([protected by email], MonthYearPickerDialog)
}.
Vote if the answer helps you.
Good luck!
Related Tags: