James
James

Reputation: 1009

How to turn off CalendarView in a DatePicker?

On my settings screen I have a date picker widget. In the designer in Eclipse, it shows as I want (3 spinners for D-M-Y) but when I test on my device, I get a rather odd view with a side spinner on the left and a calendar on the right. Never seen this before(!) but doing some research I think I'm seeing the "CalendarView".

I found that I should be able to set a "calendarViewShown" property to false- but my XML throws an error with this. I found another question on here that suggested the API level was to blame (my minSDKLevel is 7, but I'm targetting 11 so I can get the action bar button rather than the oldskool menu). So I thought I'd try setting it in code:

    int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    if (currentapiVersion >= 11)
        minDateSelector.setCalendarViewShown = false;

But again, this fails- setCalendarViewShown isn't found. But the docs here say it should exist. Any ideas?!

Upvotes: 44

Views: 47374

Answers (5)

Sca09
Sca09

Reputation: 381

I made it work with the following XML configuration:

android:datePickerMode="spinner"
android:calendarViewShown="false"

Only the following configuration didn't work for me:

android:calendarViewShown="false"

Upvotes: 15

Anshad Ali KM
Anshad Ali KM

Reputation: 1217

If you are targeting a later version of the API, you can use the following XML (no need to write Java code) in your <DatePicker>:

 android:calendarViewShown="false"

Upvotes: 97

torzech
torzech

Reputation: 404

The method in DatePicker

    public void setCalendarViewShown (boolean shown)

exists starting with API 11. If you minSdkLevel = 7 the compiler does not recognize this as a valid method - the method does not exist on android 2.3 or 2.2. The best way is to solve this is using reflection. Something like this should work properly:

int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= 11) {
  try {
    Method m = minDateSelector.getClass().getMethod("setCalendarViewShown", boolean.class);
    m.invoke(minDateSelector, false);
  }
  catch (Exception e) {} // eat exception in our case
}

Upvotes: 32

marco
marco

Reputation: 195

In those cases I use

import android.os.Build;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void someThing() {
    [...]

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        minDateSelector.setCalendarViewShown(false);
    }
}

I think the readability is better than using reflection and the style is better than catch and ignore exceptions. Of course the reflection thing is also working.

Upvotes: 10

SoloCrowd
SoloCrowd

Reputation: 51

I had the same problem as you, I couldn't make the change appear via XML.

You are on the right track, try changing your last line to:

minDateSelector.setCalendarViewShown(false);

Upvotes: 5

Related Questions