Sunday, 5 May 2013

How to show only month and year fields in android Date-picker?

Android default DatePicker show day/month/year fields but you have to customize this DatePicker as your requirements. Suppose that you want to show only month and year fields in android datepicker. To do this, you have to customize the Dialog DatePicker source code but it is not an easy task. In this tutorial I will show you a tricky way to solve this problem. Lets see how to show only month and year field in android DatePicker as a dialog.  

Step to show only month and year fields in android date-picker:

Some days ago I got this same problem and here I am trying to explain this in a sequential manner. I want to show a dialog datepicker when user click on an EditText. So if user click on EditText, A dialog datepicker will be invocked and it will show only month and year fields. To do this, at first we have to create a xml layout to hold the EditText fields. So create an android project and name it DatePickerExample. In the main.xml file just try to write this simple code. 
main.xml File: 
<RelativeLayout xmlns:android=""
    android:layout_height="match_parent" >
        android:hint="Select A Date"
        android:inputType="date" />

The MainActivity Class: 

Now the time to write the code in main activity class. 

package com.example.datepicker;
import java.lang.reflect.Field;
import java.util.Calendar;
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;

protected void onCreate(Bundle savedInstanceState) {
etPickADate = (EditText) findViewById(;
etPickADate.setOnClickListener(new OnClickListener() {

public void onClick(View arg0) {

final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);

DatePickerDialog.OnDateSetListener mDateSetListner = new OnDateSetListener() {

public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {

mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;

protected Dialog onCreateDialog(int id) {
switch (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
String localYear = Integer.toString(mYear).substring(2);
etPickADate.setText(new StringBuilder()
// Month is 0 based so add 1
.append(monthString).append("/").append(localYear).append(" "));

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")) {
DatePicker datePicker = (DatePicker) datePickerDialogField
Field datePickerFields[] = datePickerDialogField.getType()
for (Field datePickerField : datePickerFields) {
if ("mDayPicker".equals(datePickerField.getName())
|| "mDaySpinner".equals(datePickerField
.getName())) {
Object dayPicker = new Object();
dayPicker = datePickerField.get(datePicker);
((View) dayPicker).setVisibility(View.GONE);

} catch (Exception ex) {
return dpd;

Run this code and it will show only month and year field as a dialog window. It will be look like the image below.

When you click on Done text, it will put the selected month and year field in the EditText. Hope this will works fine and show the only month and year field in android datepicker. If you will find any problem with this solution, you can share your question by commenting. Also you can download the source code from here. Show only month and year field datepicker 


  1. I think eνеrything ρostеd made a bunch of sensе.
    Howevеr, conѕider this, suрpose you wrote
    a catсhier post title? I mean, Ι don't want to tell you how to run your website, but what if you added a title that makes people desire more? I mean "How to show only month and year fields in android Date-picker?" is a little vanilla. You could glance at Yahoo's
    fгοnt pаge and see hoω they create
    post tіtles to gгab people to oрen thе linκs.
    Үοu might add a vidеo oг a
    pic oг two to get people intеrestеԁ about everything've got to say. Just my opinion, it could bring your blog a little bit more interesting.

    my page :: Cheap Hotels inside Portugal

  2. I am ѕure thіѕ piece οf writing hаs touched all the
    internet users, its reallу rеally pleasant
    piece of writing on building up nеw weblog.

    Hеre is my web sіtе ... How to find Cheap Accommodations in Barcelona On the internet

  3. I drop a leave а responѕe each time I еѕpecially еnϳoy a poѕt on a
    ѕite οr I have something to аdd to
    thе convеrѕatіon. Usually it's a result of the passion communicated in the article I looked at. And after this article "How to show only month and year fields in android Date-picker?". I was moved enough to drop a commenta response ;) I actually do have a few questions for you if you don't mind.
    Is it just me oг ԁo a few of the comments appear
    like coming fгom brаіn dead
    people? :-Ρ And, if you аre posting on additionаl onlinе soсiаl sіtes, I'd like to keep up with you. Would you make a list all of your shared sites like your Facebook page, twitter feed, or linkedin profile?

    my web blog ... Have to Assess Resorts Rates?

  4. I κnoω this website offers quality depеnԁing аrticles or
    reviews anԁ additional material, is theгe anу other websіte
    which ρresеntѕ these stuff in quаlitу?

    my site ...

  5. Good way of ехрlaіning, and nice post
    to get datа аbout my presеntation subjeсt, which і am going to pгеsent іn collegе.

    Check out my sіte :: Cheap Motels In Las Vegas - Fantastic For The Short Getaway

  6. Wonderful article! We are linking to this particularly great
    article on our site. Keep up the great writing.

    Feel free to visit my webpage :: Trimextrin Diet

  7. Hi, yeah this article is really good and I
    have learned lot of things from it on the topic of blogging.

    Also visit my site - Order Trimextrin

  8. Nice blog right here! Also your website loads up very fast!
    What web host are you the usage of? Can I get your associate link in your host?
    I desire my site loaded up as quickly as yours lol

    my blog: Michael Kors

  9. This comment has been removed by the author.

  10. insert the below line also, otherwise IllegalArgumentException shown

    mDay = c.get(Calendar.DAY_OF_MONTH);

  11. How can you remove or change the title of the date picker dialog? It still shows full date

    1. You can remove Title text like this, dpd.setTitle("");

  12. We also learned the pricing could be a bit higher than our recently raised expectation, reaching as high as $400.
    The i - Phone 5 screen is 4 inches which is the biggest size when compared to all previous models
    in the i - Phone line. The new software will be available for download via i
    - Tunes on the i - Phone 4, i - Phone 4S, i
    - Phone5, and the upcoming i - Phone 5S and i - Phone 5C.

    Also visit my weblog - astuces pour Clash of clans

  13. This code does not work in ICS :(

  14. Great blog right here! Also your web site rather a lot up very fast!
    What host are you the usage of? Can I am getting
    your affiliate hyperlink to your host? I wish my web site loaded
    up as fast as yours lol

    Feel free to surf to my page: Nike Blazers Leather

  15. Another plus is the all-metal construction, a truly retro touch.
    What this means, to the casual photographer, is the picture
    you take will be the same as the image you
    view through the lens. Let's look at a few of the best models, all have an average
    retail price under $1000.

    Look into my website: canon rebel sl1

  16. Quality content is the important to interest the
    users to go to see the web site, that's what this web page is providing.

    Also visit my site ... gas grill parts

  17. You can of course hire these people based on experience or recommendation. Each year they were able to generate
    enough revenue to pay for the ad, keep the repairmen busy and add a new truck or two to their fleet.
    This option pinpoints your current location on the map,
    at which point you can 'find a location', make a 'local search' or 'get
    directions'. Construction project managers must conduct these tasks prior to starting on a construction project.
    The Internet Movie Database credits this
    as being the first movie based on a video game, but that’s something I always attributed to the 1984 movie called Cloak & Dagger.
    Some modern systems use micro-bore copper piping which now can be supplied in insulated coils, making for easier
    installation and longer runs without pipe fitting joints.
    Hiring tree removal services does not only involve this one job.
    Talking about the portals involves in the contacts of plumbers in Birmingham, these portals
    have extensive data of tradesmen from all the areas of the
    country. Be suspicious of any plumber who won't provide either of these
    things. The education and training required to become a qualified
    plumber should give some indication of the fact that, whatever else you might call it, plumbing isn't always easy.

    Review my web page ... boca raton my pink plumber reviews

  18. However, without employing SEO, the task is half done.
    In order to figure out the best SEO consulting service in your area, you should
    go through the product reviews. It is essential that the company you work with
    has clear communication, a proven track record, and the knowledge and ability to improve your rankings as they have

    my blog post - PPH gig

  19. Very good info. Lucky me I came across your website by
    accident (stumbleupon). I've saved it for later!

    Also visit my site questions to ask a girl

  20. New grownup webcam performers can count on to generate
    $2000 to $5000 inside their really initially month working as tiny as two
    hrs day, although top doing models could make above $20,000 just about
    every month. They can be annoying, but understand oftentimes potential paying
    members. "And greater content they generate, the greater is watched, and the more sales are made.

    Feel free to surf to my blog post; webcam girl reviews (

  21. For most recent news you have to visit world-wide-web and on world-wide-web I found this
    site as a finest web site for hottest updates.

    My web blog - Hidroizolatii terase ()

  22. Does your site have a contact page? I'm having problems locating it but, I'd like to send you an e-mail.

    I've got some recommendations for your blog you might be interested in hearing.
    Either way, great website and I look forward too seeing it grow over time.

    My web-site iron force cheats

  23. A lot of spam in the comments. Thanks for the code.

  24. One function of the bustle and the hoopskirt was to make the waist
    look smaller and to enhance the bust. Instead try
    a nice pair of wool or cotton chino dress trousers with a button down shirt, sweater vest, tie, and sport jacket.
    Being a model requires more than just being a pretty face.

    Feel free to surf to my web page ... bandage js collection dresses boutique

  25. Your mouth watering chicken salad is ready to
    serve. Blood HCG test: What is the best time for early pregnancy test.
    ,” keep in mind that the h - CG weight loss plan works because you're taking the h - CG hormone in injection, oral drop
    or pill form during the time you're on the 500 calorie per day diet.

    Here is my blog :: best hcg sublingual drops

  26. Jarred stijgen wind verwacht, wordt de geest zwaar beschadigd, de wind die samen vliegen is een direct Uggs Kinder Bestellen bloed uitgeworpen. Hoe Ugg Bailey Button Goedkope Bestellen kon de magie.  wind gedwongen golvende bloeddruk, ik hoorde consternatie .

    Ugg Bailey Button Goedkope Bestellen palm te doden een klap in het voordeel van opvallende fel naar de rechterpols. Uggs Heren Bestellen zijn handen op zijn taille tas geborsteld besparingen, het volgende moment zag ik twee bloedige Ugg Bailey Button Goedkope Bestellen Vork verscheen in de handen. Bang.

    Ugg Bailey Button Goedkope Ugg Bailey Button Goedkope Bestellen Bestellen donkerblauwe kleine bel vloog. Belletje dat liquideren, en direct omgezet in voet acht meter hoge Ugg Bailey Button Goedkope Bestellen bell mond diameter groot genoeg om vijf meter van de bel te hebben. Zie de beenderen van de palm van gaat.


//infolinks add placement