Search code examples
androidandroid-datepicker

Datepicker has probably the wrong style


Why does my datepicker doesn't look like a normal one with 3 of those scroll things?

http://i.imgur.com/lk2ZddE.jpg

Code:

<DatePicker android:id="@+id/datePicker1" 
            style="android:datePicker1" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" />

Solution

  • Datepicker is a bit buggy from android 3.2 and up. Here's some code that will extend and modify the datepicker:

    import android.content.Context;
    import android.util.AttributeSet;
    import android.view.MotionEvent;
    import android.view.ViewParent;
    import android.widget.DatePicker;
    
    public class CustomDatePicker extends DatePicker
    {
        public CustomDatePicker(Context context, AttributeSet attrs, int
    defStyle)
        {
            super(context, attrs, defStyle);
        }
    
        public CustomDatePicker(Context context, AttributeSet attrs)
        {
            super(context, attrs);
        }
    
        public CustomDatePicker(Context context)
        {
            super(context);
        }
    
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev)
        {
            /* Prevent parent controls from stealing our events once we've
    gotten a touch down */
            if (ev.getActionMasked() == MotionEvent.ACTION_DOWN)
            {
                ViewParent p = getParent();
                if (p != null)
                    p.requestDisallowInterceptTouchEvent(true);
            }
    
            return false;
        }
    }
    

    And to utilise it with XML:

    <view android:id="@+id/datePicker" android:layout_width="fill_parent" 
    android:layout_height="wrap_content" class="YOUR_PACKAGE.CustomDatePicker"   
     android:calendarviewshown="false">
            </view>
    

    I've always used a custom view when I put it directly in my XML layout. Might be bad practice, I'm not sure. I'd appreciate a comment from someone if it is.