Sunday, 5 May 2013

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

14 comments
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="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <EditText
        android:id="@+id/et_datePicker"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Select A Date"
        android:inputType="date" />
</RelativeLayout>

The MainActivity Class: 

Now the time to write the code in main activity class. 
MainActivity.java: 

package com.example.datepicker;
import java.lang.reflect.Field;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DatePickerDialog.OnDateSetListener;
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;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etPickADate = (EditText) findViewById(R.id.et_datePicker);
etPickADate.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
showDialog(DATE_DIALOG_ID);
}
});

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

DatePickerDialog.OnDateSetListener mDateSetListner = new OnDateSetListener() {

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

mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDate();
}
};

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

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")) {
datePickerDialogField.setAccessible(true);
DatePicker datePicker = (DatePicker) datePickerDialogField
.get(dpd);
Field datePickerFields[] = datePickerDialogField.getType()
.getDeclaredFields();
for (Field datePickerField : datePickerFields) {
if ("mDayPicker".equals(datePickerField.getName())
|| "mDaySpinner".equals(datePickerField
.getName())) {
datePickerField.setAccessible(true);
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. Download Source Code: Show only month and year field datepicker 

14 comments:

  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

    ReplyDelete
  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

    ReplyDelete
  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?

    ReplyDelete
  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 ... http://www.hotel-discount.com/boutique-hotels/

    ReplyDelete
  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

    ReplyDelete
  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

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

    Also visit my site - Order Trimextrin

    ReplyDelete
  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

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. insert the below line also, otherwise IllegalArgumentException shown

    mDay = c.get(Calendar.DAY_OF_MONTH);

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

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

      Delete
  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

    ReplyDelete
  13. This code does not work in ICS :(

    ReplyDelete