用AndroidWheel自定义DatePicker及DatePickerDialog

自定义DatePicker及DatePickerDialog

利用开源项目AndroidWheel,地址:https://code.google.com/p/android-wheel/,自定义DatePicker及DatePickerDialog

CustomDatePicker布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res/com.example.testapp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:gravity="center" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal" >

        <com.example.testapp.wheel.WheelVerticalView
            android:id="@+id/year"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:unselectedAlpha="0.5"
            app:visibleItems="4" />

        <com.example.testapp.wheel.WheelVerticalView
            android:id="@+id/month"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:unselectedAlpha="0.5"
            app:visibleItems="4" />

        <com.example.testapp.wheel.WheelVerticalView
            android:id="@+id/day"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:unselectedAlpha="0.5"
            app:visibleItems="4" />
    </LinearLayout>

</LinearLayout>

CustomDatePicker代码

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import com.example.testapp.R;
import com.example.testapp.wheel.AbstractWheel;
import com.example.testapp.wheel.AbstractWheelTextAdapter;
import com.example.testapp.wheel.ArrayWheelAdapter;
import com.example.testapp.wheel.OnWheelScrollListener;
import com.example.testapp.wheel.WheelVerticalView;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

public class CustomDatePicker extends LinearLayout {
    private WheelVerticalView year;
    private WheelVerticalView month;
    private WheelVerticalView day;
    private ChangingListener listener;

    private ArrayWheelAdapter adapter3;
    private Context context;
    private Calendar select_date;
    private Calendar now_date;

    public CustomDatePicker(final Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        View v = LayoutInflater.from(context).inflate(
                R.layout.custom_datepicker, null);
        year = (WheelVerticalView) v.findViewById(R.id.year);
        month = (WheelVerticalView) v.findViewById(R.id.month);
        day = (WheelVerticalView) v.findViewById(R.id.day);

        ArrayList<String> yearlist = new ArrayList<String>();
        ArrayList<String> monthlist = new ArrayList<String>();

        for (int i = 1901; i < 2900; i++) {
            yearlist.add(i + "年");

        }

        for (int i = 1; i <= 12; i++) {
            monthlist.add(i + "月");
        }

        ArrayWheelAdapter adapter1 = new ArrayWheelAdapter(context,
                yearlist.toArray());

        ArrayWheelAdapter adapter2 = new ArrayWheelAdapter(context,
                monthlist.toArray());
        adapter3 = new ArrayWheelAdapter(context, getDaylist(31).toArray());
        setTextColor(adapter1);
        setTextColor(adapter2);
        setTextColor(adapter3);
        year.setViewAdapter(adapter1);
        month.setViewAdapter(adapter2);
        day.setViewAdapter(adapter3);
        year.setCyclic(true);
        month.setCyclic(true);
        day.setCyclic(true);
        setDate(Calendar.getInstance());

        OnWheelScrollListener scrollListener = new OnWheelScrollListener() {

            @Override
            public void onScrollingStarted(AbstractWheel wheel) {
                select_date = getDate();

            }

            @Override
            public void onScrollingFinished(AbstractWheel wheel) {

                if (now_date != null) {
                    Calendar date = getDate();
                    int compareTo = date.compareTo(now_date);

                    if (compareTo < 0) {
                        setDate(select_date);

                        Toast.makeText(getContext(), "不能选择此日期",
                                Toast.LENGTH_SHORT).show();

                    }

                }

                setDayAdapter();

            }
        };

        OnWheelScrollListener scrollListener1 = new OnWheelScrollListener() {

            @Override
            public void onScrollingStarted(AbstractWheel wheel) {
                select_date = getDate();

            }

            @Override
            public void onScrollingFinished(AbstractWheel wheel) {

                if (now_date != null) {
                    Calendar date = getDate();
                    int compareTo = date.compareTo(now_date);

                    if (compareTo < 0) {
                        setDate(select_date);
                        Toast.makeText(getContext(), "不能选择此日期",
                                Toast.LENGTH_SHORT).show();
                    }

                }
                doListener();

            }
        };
        month.addScrollingListener(scrollListener);
        year.addScrollingListener(scrollListener);
        day.addScrollingListener(scrollListener1);

        addView(v);

    }

    private List getDaylist(int num) {
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 1; i <= num; i++) {
            String d = i + "日";
            if (i < 10) {
                d = "\t" + i + "日";
            }
            list.add(d);
        }
        return list;

    }

    private void doListener() {
        if (listener != null) {
            listener.onChange(getDate());
        }

    }

    public interface ChangingListener {

        void onChange(Calendar c);
    }

    private void setDayAdapter() {
        int currentItem = year.getCurrentItem();
        int current = currentItem + 1901;
        int newValue = month.getCurrentItem() + 1;
        switch (newValue) {

        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:

            adapter3 = new ArrayWheelAdapter(context, getDaylist(31).toArray());

            break;
        case 2:
            if (current % 4 == 0) {
                adapter3 = new ArrayWheelAdapter(context, getDaylist(29)
                        .toArray());
            } else {
                adapter3 = new ArrayWheelAdapter(context, getDaylist(28)
                        .toArray());
            }

            break;

        case 4:
        case 6:
        case 9:
        case 11:
            adapter3 = new ArrayWheelAdapter(context, getDaylist(30).toArray());
            break;
        default:
            break;
        }
        day.setViewAdapter(adapter3);
        setTextColor(adapter3);
        doListener();

    }

    /**
     * 设置初始日期
     * 
     * @param c
     */
    public void setDate(Calendar c) {
        int y = c.get(Calendar.YEAR);
        int index1 = y - 1901;
        year.setCurrentItem(index1);
        int m = c.get(Calendar.MONTH);

        month.setCurrentItem(m);
        int d = c.get(Calendar.DAY_OF_MONTH);
        setDayAdapter();
        day.setCurrentItem(d - 1);

    }

    /**
     * 设置字体颜色
     * 
     * @param adapter
     */
    public void setTextColor(AbstractWheelTextAdapter adapter) {
        adapter.setTextColor(context.getResources().getColor(R.color.blue));
    }

    /**
     * 设置限制日期,设置后,不能选择设置的开始日期以前的日期
     * 
     * @param c
     */
    public void setNowData(Calendar c) {
        now_date = c;
    }

    /**
     * 得到日期
     * 
     * @return
     */
    public Calendar getDate() {
        int y = year.getCurrentItem();
        int index1 = y + 1901;
        int m = month.getCurrentItem();
        int d = day.getCurrentItem();
        Calendar c = Calendar.getInstance();
        c.set(index1, m, d + 1);

        return c;
    }

    /**
     * 设置日期改变的监听
     * 
     * @param listener
     */
    public void addChangingListener(ChangingListener listener) {
        this.listener = listener;

    }

}

CustomDatePickerDialog布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="270dp"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:background="@drawable/white_round_shape"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_dialog_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="10dp"
        android:text="请选择日期"
        android:textColor="@color/black"
        android:textSize="18sp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/blue" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/tv_dialog_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:text="2014年11月5日"
            android:textColor="@color/black"
            android:textSize="15sp" />
    </LinearLayout>

    <com.example.testapp.view.CustomDatePicker
        android:id="@+id/cdp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center|right"
        android:orientation="horizontal"
        android:paddingBottom="10dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="10dp" >

        <TextView
            android:id="@+id/tv_cancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="10dp"
            android:text="取消"
            android:textColor="@color/yellow2gray_selector"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/tv_sure"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"

            android:gravity="center"
            android:padding="10dp"
            android:text="确定"
            android:textColor="@color/blue2gray_selector"
            android:textSize="18sp" />
    </LinearLayout>

</LinearLayout>

CustomDatePickerDialog代码

import java.text.SimpleDateFormat;
import java.util.Calendar;

import com.example.testapp.R;
import com.example.testapp.view.CustomDatePicker.ChangingListener;

import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class CustomDatePickerDialog extends Dialog {

    private TextView tv_sure;
    private TextView tv_cancel;
    private onDateListener listener;
    private Calendar c = Calendar.getInstance();
    private CustomDatePicker cdp;

    public CustomDatePickerDialog(Context context, Calendar c) {
        super(context, R.style.CustomDialog);
        this.c = c;

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.custom_datepicker_dialog);
        getWindow().setBackgroundDrawable(new BitmapDrawable());
        setCanceledOnTouchOutside(true);
        TextView tv_dialog_title = (TextView) findViewById(R.id.tv_dialog_title);
        final TextView tv_dialog_content = (TextView) findViewById(R.id.tv_dialog_content);
        tv_sure = (TextView) findViewById(R.id.tv_sure);
        tv_cancel = (TextView) findViewById(R.id.tv_cancel);

        cdp = (CustomDatePicker) findViewById(R.id.cdp);

        cdp.setDate(c);

        SimpleDateFormat sdfFrom = new SimpleDateFormat("yyyy年MM月dd日 E");
        String string = sdfFrom.format(c.getTime());

        tv_dialog_content.setText(string);

        cdp.addChangingListener(new ChangingListener() {

            @Override
            public void onChange(Calendar c1) {
                c = c1;
                SimpleDateFormat sdfFrom = new SimpleDateFormat("yyyy年MM月dd日 E");
                String string = sdfFrom.format(c.getTime());

                tv_dialog_content.setText(string);

            }
        });
        View.OnClickListener clickListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (v == tv_sure) {
                    if (listener != null) {
                        listener.dateFinish(c);
                    }

                }
                dismiss();
            }
        };

        tv_sure.setOnClickListener(clickListener);
        tv_cancel.setOnClickListener(clickListener);

    }
    /**
     * 设置限制日期,设置后,不能选择设置的开始日期以前的日期
     * 
     * @param c
     */
    public void setNowData(Calendar c) {
        cdp.setNowData(c);

    }
    /**
     * 设置点击确认的事件
     * 
     * @param listener
     */
    public void addDateListener(onDateListener listener) {
        this.listener = listener;
    }

    public interface onDateListener {
        void dateFinish(Calendar c);
    }

}

使用方法

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.tv_click).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                CustomDatePickerDialog dialog = new CustomDatePickerDialog(MainActivity.this, Calendar.getInstance());
                dialog.addDateListener(new onDateListener() {

                    @Override
                    public void dateFinish(Calendar c) {
                        Toast.makeText(getApplicationContext(), c.getTime().toLocaleString(), Toast.LENGTH_SHORT).show();

                    }
                });

                dialog.show();

            }
        });

        CustomDatePicker cdp = (CustomDatePicker) findViewById(R.id.cdp);
        cdp.addChangingListener(new ChangingListener() {

            @Override
            public void onChange(Calendar c) {
                Toast.makeText(getApplicationContext(), c.getTime().toLocaleString(), Toast.LENGTH_SHORT).show();

            }
        });

    }

运行效果:

技术分享
技术分享

示例代码下载地址:http://download.csdn.net/detail/u014580558/8528109

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。