自定义日历控件-——Android

发布时间:2020-07-26 10:44:36 作者:sly920224
来源:网络 阅读:5480

    

    这几天公司出了签到的需求,让我来做签到这一块,刚开始以为非常好做,不就是调用系统的日历吗。系统的日历与签到标签基于足够完成了。我首先用Android5.0以上的机器调用了日历控件,发现还不错,但是用了一台4.2的机器调用日历。我靠!这丑不拉几,看着都要吐了还能用?没有办法,我只能尝试自定义日历控件了。

    下面是设计给的我第一张图:

                  自定义日历控件-——Android

刚开始我想的是可以画为6行7列的网格,GridView可以实现,正准备做,可是下午设计又给了我一张图:

                  自定义日历控件-——Android

    大白圈是今天的日期,小白点是这个月已签过到的日期,黑色字体是已经过去的日期,灰色是还没有到来的日期。这变化有点大啊,这要的话用GridView就得区分好几种不同的Type了,如果以后还有其他加的不是会更麻烦,然后只能自己画View这样,自己对这个View很熟悉,以后要添加什么功能可以很清楚的加上代码。

    于是我就在网上搜Android自定义日历控件,当我在CSDN上看到zou128865写的Android UI-自定义日历控件正好能满足我目前的需求,于是我就把他的代码下载下来,仔细的研究。在他的代码上修改变成我自己的日历控件。好啦废话不多说了,开始我们的日历控件之旅吧。 


        当我要做完这个控件的时候,设计发来了最终稿的动态图:不能上传完整的动态不然老板搞死我,见谅哈。

            自定义日历控件-——Android

不会上传动态图呀 !!!!!!

    来开始代码:

1.CalendarView:


package oct.mama.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;

import java.util.List;

import oct.mama.R;
import oct.mama.model.CustomDateModel;
import oct.mama.utils.CheckInUtils;
import oct.mama.utils.CountDownTimerUtils;

/**
 * 日历展示控件
 * Created by Administrator on 2015/10/29.
 */
public class CalendarView extends View {
    private static final int TOTAL_COL = 7; // 7列
    private static final int TOTAL_ROW = 6; // 6行

    private Paint mCirclePaint; // 绘制圆形的画笔
    private Paint mTextPaint; // 绘制文本的画笔
    private int mViewWidth; // 视图的宽度
    private int mViewHeight; // 视图的高度
    private int mCellSpace; // 单元格列间距
    private int mCellRowSpace; // 单元行间距
    private Paint mRowTextPaint;
    private Row rows[] = new Row[TOTAL_ROW]; // 行数组,每个元素代表一行
    private static CustomDateModel mShowDate; // 自定义的日期,包括year,month,day
    private OnCellClickListener mCellClickListener; // 单元格点击回调事件
    private int touchSlop; //事件触发最小距离

    private Cell mClickCell;
    private float mDownX;
    private float mDownY;
    private int circleRadius;
    private float currentDayX;
    private float currentDayY;
    private int currentMonthDays; // 当前月天数

    private List<Long> checkInDays; // 服务器传来已签过的days
    private int checkIndex = 0; // 遍历checkInDays角标,每次onDarw时要将脚表归0,不然有时候会出现闪烁问题
    private long serverTime; //服务器传来时间
    private CheckInUtils mCheckInUtils;

    

    /**
     * 单元格点击的回调接口
     *
     * @author wuwenjie
     *
     */
    public interface OnCellClickListener {
        void changeDate(CustomDateModel date); // 回调滑动ViewPager改变的日期
    }


    public CalendarView(Context context, OnCellClickListener listener, long serverTime) {
        super(context);
        this.mCellClickListener = listener;
        this.serverTime = serverTime;
        this.mCheckInUtils = CheckInUtils.getInstance();
        init(context);
    }

    private void init(Context context) {
        if (mCheckInUtils != null){
            mCheckInUtils.setServerTime(serverTime);
        }
        mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mRowTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mCirclePaint.setStyle(Paint.Style.FILL);
        mCirclePaint.setColor(getResources().getColor(R.color.log_today_white_circle)); // 白色圆圈
        touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        this.setBackgroundResource(R.color.log_today_calendar_bg);//控件背景
        initDate();
    }

    private void initDate() {
        mShowDate = new CustomDateModel(serverTime);//系统时间可能被更改,所以从服务器获取时间,(防刷)
        fillDate();//
    }

    /**
     * 填充数据
     */
    private void fillDate() {
        int monthDay = mCheckInUtils.getCurrentMonthDay(); // 今天
        int lastMonthDays = mCheckInUtils.getMonthDays(mShowDate.year,
                mShowDate.month - 1); // 上个月的天数
        currentMonthDays = mCheckInUtils.getMonthDays(mShowDate.year,
                mShowDate.month); // 当前月的天数
        int firstDayWeek = mCheckInUtils.getWeekDayFromDate(mShowDate.year,
                mShowDate.month);
        boolean isCurrentMonth = false;
        if (mCheckInUtils.isCurrentMonth(mShowDate)) {
            isCurrentMonth = true;
        }
        int day = 0;

        /*
        *判断当月位置,并对其设置对应的状态、数字。
         */
        for (int j = 0; j < TOTAL_ROW; j++) {//6行
            rows[j] = new Row(j);
            for (int i = 0; i < TOTAL_COL; i++) {//7列
                int position = i + j * TOTAL_COL; // 单元格位置
                // 这个月的
                if (position >= firstDayWeek
                        && position < firstDayWeek + currentMonthDays) {
                    day++;
                    rows[j].cells[i] = new Cell(CustomDateModel.modifiDayForObject(
                            mShowDate, day), State.CURRENT_MONTH_DAY, i, j);
                    //还没到时间的字体颜色都比较淡
                    if (mShowDate.getYear() > mCheckInUtils.getYear() ||
                            (mShowDate.getYear() == mCheckInUtils.getYear() && mShowDate.getMonth() > mCheckInUtils.getMonth())){
                        rows[j].cells[i] = new Cell(
                                CustomDateModel.modifiDayForObject(mShowDate, day),
                                State.UNREACH_DAY, i, j);
                    }
                    // 今天
                    if (isCurrentMonth && day == monthDay ) {
                        CustomDateModel date = CustomDateModel.modifiDayForObject(mShowDate, day);
                        rows[j].cells[i] = new Cell(date, State.TODAY, i, j);
                    }

                    if (isCurrentMonth && day > monthDay) { // 如果比这个月的今天要大,表示还没到
                        rows[j].cells[i] = new Cell(
                                CustomDateModel.modifiDayForObject(mShowDate, day),
                                State.UNREACH_DAY, i, j);
                    }

                    // 过去一个月
                } else if (position < firstDayWeek) {
                    rows[j].cells[i] = new Cell(new CustomDateModel(mShowDate.year,
                            mShowDate.month - 1, lastMonthDays
                            - (firstDayWeek - position - 1)),
                            State.PAST_MONTH_DAY, i, j);
                    // 下个月
                } else if (position >= firstDayWeek + currentMonthDays) {
                    rows[j].cells[i] = new Cell((new CustomDateModel(mShowDate.year,
                            mShowDate.month + 1, position - firstDayWeek
                            - currentMonthDays + 1)),
                            State.NEXT_MONTH_DAY, i, j);
                }
            }
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mViewWidth = w;
        mViewHeight = h;
        mCellSpace =  mViewWidth / TOTAL_COL; //每个框格宽度
        mCellRowSpace = mViewHeight/TOTAL_ROW;//每个框格高度
        circleRadius = mCellSpace / 3;
        mTextPaint.setTextSize(mCellSpace / 4);
        mRowTextPaint.setTextSize(mCellRowSpace / 4);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        checkIndex = 0;
        for (int i = 0; i < TOTAL_ROW; i++) {
            if (rows[i] != null) {
                rows[i].drawCells(canvas);
            }
        }
    }

    /**
    *目前还没用到为以后补签做准备
    *
    */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mDownX = event.getX();
                mDownY = event.getY();
                break;
            case MotionEvent.ACTION_UP:
                float disX = event.getX() - mDownX;
                float disY = event.getY() - mDownY;
                if (Math.abs(disX) < touchSlop && Math.abs(disY) < touchSlop) {
                    int col = (int) (mDownX / mCellSpace);
                    int row = (int) (mDownY / mCellRowSpace);
                    measureClickCell(col, row);
                }
                break;
            default:
                break;
        }

        return true;
    }

    /**
     * 计算点击的单元格
     * @param col
     * @param row
     */
    private void measureClickCell(int col, int row) {
        if (col >= TOTAL_COL || row >= TOTAL_ROW)
            return;
        if (mClickCell != null) {
            rows[mClickCell.j].cells[mClickCell.i] = mClickCell;
        }
        if (rows[row] != null) {
            mClickCell = new Cell(rows[row].cells[col].date,
                    rows[row].cells[col].state, rows[row].cells[col].i,
                    rows[row].cells[col].j);

            CustomDateModel date = rows[row].cells[col].date;
            date.week = col;
            // 刷新界面
            update();
        }
    }

    /**
     * 组元素
     *
     */
    class Row {
        public int j;

        Row(int j) {
            this.j = j;
        }

        public Cell[] cells = new Cell[TOTAL_COL];

        // 绘制单元格
        public void drawCells(Canvas canvas) {
            for (int i = 0; i < cells.length; i++) {
                if (cells[i] != null) {
                    cells[i].drawSelf(canvas);
                }
            }
        }

    }

    /**
     * 单元格元素
     *
     * @author wuwenjie
     *
     */
    class Cell {
        public CustomDateModel date;
        public State state;
        public int i;
        public int j;

        public Cell(CustomDateModel date, State state, int i, int j) {
            super();
            this.date = date;
            this.state = state;
            this.i = i;
            this.j = j;
        }

        public void drawSelf(Canvas canvas) {
            String content = String.valueOf(date.day);
            switch (state) {
                case TODAY: // 今天
                    mTextPaint.setColor(getResources().getColor(R.color.log_today_current_text));
                    currentDayX = (float) (mCellSpace * (i + 0.55));
                    currentDayY = (float) ((j + 0.48) * mCellRowSpace);
                    canvas.drawCircle(currentDayX, currentDayY, circleRadius -10, mCirclePaint);
                    break;
                case CURRENT_MONTH_DAY: // 当前月日期
                    mTextPaint.setColor(getResources().getColor(R.color.log_today_current_text));
                    if (checkInDays != null) {
                        if (checkIndex < checkInDays.size()) {
                            if ((checkInDays.get(checkIndex) % 100 == date.day)) {
                                canvas.drawCircle((float) (mCellSpace * (i + 0.55)), (float) (j + 0.9) * mCellRowSpace, 4, mCirclePaint);
                                checkIndex++;
                            }
                        }
                    }
                    break;
                case PAST_MONTH_DAY: // 过去一个月
                case NEXT_MONTH_DAY: // 下一个月
                    mTextPaint.setColor(getResources().getColor(R.color.log_today_calendar_bg));
                    break;
                case UNREACH_DAY: // 还未到的天
                    mTextPaint.setColor(Color.GRAY);
                    break;
                default:
                    break;
            }
            // 绘制文字
            canvas.drawText(content,
                    (float) ((i+0.55) * mCellSpace - mTextPaint
                            .measureText(content) / 2), (float) ((j + 0.7)
                            * mCellRowSpace - mRowTextPaint
                            .measureText(content, 0, 1) / 2), mTextPaint);
        }
    }

    /**
     *
     * @author wuwenjie 单元格的状态 当前月日期,过去的月的日期,下个月的日期
     */
    enum State {
        TODAY,CURRENT_MONTH_DAY, PAST_MONTH_DAY, NEXT_MONTH_DAY, UNREACH_DAY;
    }

    // 从左往右划,上一个月
    public void leftSlide() {
        checkInDays = null;
        if (mShowDate.month == 1) {
            mShowDate.month = 12;
            mShowDate.year -= 1;
        } else {
            mShowDate.month -= 1;
        }
        if(mCellClickListener != null){
            mCellClickListener.changeDate(mShowDate);
        }
        update();
    }

    // 从右往左划,下一个月
    public void rightSlide() {
        checkInDays = null;
        if (mShowDate.month == 12) {
            mShowDate.month = 1;
            mShowDate.year += 1;
        } else {
            mShowDate.month += 1;
        }
        if(mCellClickListener != null){
            mCellClickListener.changeDate(mShowDate);
        }
        update();
    }

    public void update(){
        checkIndex = 0;
        fillDate();
        invalidate();
    }

    public void currentUpdate(){
        initDate();
        if(mCellClickListener != null){
            mCellClickListener.changeDate(mShowDate);
        }
        invalidate();
    }

    /**
     * 当月已签days(正确时间)
     */
    public void setCurrentCheckInDays(List<Long> currentLogs){
        this.checkInDays = currentLogs;
        initDate();
        if(mCellClickListener != null){
            mCellClickListener.changeDate(mShowDate);
        }
        invalidate();
    }

    /**
     * 本月已签
     * @param logs
     */
    public void setCheckInDays(List<Long> logs){
        this.checkInDays = logs;
        update();
    }
    /**
     * 签到刷新方法,并返回当前日期坐标(放大)
     * @return
     */
    public void SignIn(){
        new CountDownTimerUtils(350, 25) {
            @Override
            public void onTick(long millisUntilFinished) {
                fillDate();
                circleRadius = circleRadius +1;
                invalidate();
            }
            @Override
            public void onFinish() {
                cancel();
                SignInt();
            }
        }.start();
    }

    /**
     * (缩小)
     */
    private  void SignInt(){
        new CountDownTimerUtils(350 , 25) {
            @Override
            public void onTick(long millisUntilFinished) {
                fillDate();
                circleRadius = circleRadius -1;
                invalidate();
            }
            @Override
            public void onFinish() {
                cancel();
            }
        }.start();
    }
}


2.CheckInUtils

    工具类,主要是从Calendar中获取日期,注意不要因为mCalender = Calender.getInstance就以为Calender是单例,我这这地方吃过亏。

package oct.mama.utils;

import android.annotation.SuppressLint;
import android.content.Context;

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

import oct.mama.model.CustomDateModel;

/**
 * 签到日期工具, 调用除设置或获取参数外得先调用setServerTime函数;
 * Created by Administrator on 2015/10/29.
 */
public class CheckInUtils {

    private static CheckInUtils checkInUtils = new CheckInUtils();
    public static final String CHECK_IN_KEY = "check_in_time";//签到key
    public Calendar mCalender;
    private CheckInUtils(){

    }
    public static CheckInUtils getInstance(){
        return checkInUtils;
    }

    public void setServerTime(long time){
        mCalender = Calendar.getInstance();
        mCalender.setTimeInMillis(time*1000);
    }

    public int getMonthDays(int year, int month) {
        if (month > 12) {
            month = 1;
            year += 1;
        } else if (month < 1) {
            month = 12;
            year -= 1;
        }
        //月份对应的天数
        int[] arr = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        int days = 0;

        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
            arr[1] = 29; // 闰年2月29天
        }

        try {
            days = arr[month - 1];
        } catch (Exception e) {
            e.getStackTrace();
        }

        return days;
    }
    public int getYear() {
        return mCalender.get(Calendar.YEAR);
    }

    public String getCurrentTime(){
        return mCalender.get(Calendar.YEAR)+"-"+ checkInUtils.getMonth();
    }

    public int getMonth() {
        return mCalender.get(Calendar.MONTH) + 1;
    }

    public int getCurrentMonthDay() {
        return mCalender.get(Calendar.DAY_OF_MONTH);
    }
    /**
     * 当月1号是第一个星期的第几天
     * @param year
     * @param month
     * @return
     */
    public int getWeekDayFromDate(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(getDateFromString(year, month));
        int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (week_index < 0) {
            week_index = 0;
        }
        return week_index;
    }

    @SuppressLint("SimpleDateFormat")
    public Date getDateFromString(int year, int month) {
        String dateString = year + "-" + (month > 9 ? month : ("0" + month))
                + "-01";
        Date date = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            date = sdf.parse(dateString);
        } catch (ParseException e) {
            System.out.println(e.getMessage());
        }
        return date;
    }

    public boolean isCurrentMonth(CustomDateModel date){
        return(date.year == checkInUtils.getYear() &&
                date.month == checkInUtils.getMonth());
    }

    /**
     * 本地保存签到记录
     */
    public static void savePreference(Context context){
        SharedPreferencesUtils.setPreferenceLong(context, CHECK_IN_KEY,
                System.currentTimeMillis() / 1000 / 60 / 60 / 24);
    }

    public static long getPreference(Context context){
        return SharedPreferencesUtils.getPreferenceLong(context, CHECK_IN_KEY, 0);
    }

}


3.CustomDateModel

package oct.mama.model;

import oct.mama.utils.CheckInUtils;

/**
 * 签到日期实体类
 * Created by Administrator on 2015/10/29.
 */
public class CustomDateModel {

    public int year;
    public int month;
    public int day;
    public int week;

    public CustomDateModel(int year, int month, int day){
        if(month > 12){
            month = 1;
            year++;
        }else if(month <1){
            month = 12;
            year--;
        }
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public CustomDateModel(long serverTime){
        CheckInUtils mCheckInUtils = CheckInUtils.getInstance();
        mCheckInUtils.setServerTime(serverTime);
        this.year = mCheckInUtils.getYear();
        this.month = mCheckInUtils.getMonth();
        this.day = mCheckInUtils.getCurrentMonthDay();
    }

    public static CustomDateModel modifiDayForObject(CustomDateModel date,int day){
        CustomDateModel modifiDate = new CustomDateModel(date.year,date.month,day);
        return modifiDate;
    }
    @Override
    public String toString() {
        return year+"-"+month+"-"+day;
    }

    public String getTime(){
        return year+"-"+month;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    public int getWeek() {
        return week;
    }

    public void setWeek(int week) {
        this.week = week;
    }

}


4.Activity:

注意在我请求数据的那些地方大家要填充自己的值。删除了许多跟公司相关的东西。

package oct.mama.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;

import java.text.MessageFormat;
import java.util.List;

import oct.mama.R;
import oct.mama.adapter.CalendarViewAdapter;
import oct.mama.alert.CheckInRuleDialog;
import oct.mama.alert.ConfirmDialog;
import oct.mama.api.ApiInvoker;
import oct.mama.apiInterface.IMemberApi;
import oct.mama.apiResult.GenericResult;
import oct.mama.connect.GenericResultResponseHandler;
import oct.mama.model.CheckInResult;
import oct.mama.model.CouponInfoModel;
import oct.mama.model.CustomDateModel;
import oct.mama.model.MonthSignLogModel;
import oct.mama.model.ShowCheckInResult;
import oct.mama.utils.CheckInUtils;
import oct.mama.view.CalendarView;

/**
 * 签到页面
 */
public class CheckInActivity extends BaseTitleActivity implements  CalendarView.OnCellClickListener, View.OnClickListener {
    private ViewPager mViewPager;
    public List<Long> currentLogs;

    private TextView couponRmb;
    private TextView couponArea;
    private ImageView logTodayBgImageView;
 
    private TextView monthText;
    private ImageView signInImageView;
    private TextView animText;

    private int mCurrentIndex = 498;
    private CalendarView[] mShowViews;
    private CalendarViewAdapter<CalendarView> adapter;
    private SildeDirection mDirection = SildeDirection.NO_SILDE;

    private CheckInRuleDialog checkInRuleDialog;

    private IMemberApi mIMemberApi;

    private int continuousDays;
    private CheckInUtils mCheckInUtils;
    private String rules;
    private String currentAmount;
    private String currentArea;
    enum SildeDirection {
        RIGHT, LEFT, NO_SILDE;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_log_today);

        setTitleText(R.string.log_have_gift);

        init();
        mCheckInUtils =CheckInUtils.getInstance();
        CheckInUtils.savePreference(this);//本地保存签到记录
        getCheckInData();
    }

    private void init(){
        
        ImageView preImgBtn = (ImageView) findViewById(R.id.last_month);
        ImageView nextImgBtn = (ImageView) findViewById(R.id.next_month);
        monthText = (TextView) findViewById(R.id.log_today_time);
        signInImageView = (ImageView) findViewById(R.id.log_today_check);
        mViewPager = (ViewPager) this.findViewById(R.id.vp_calendar);
        animText = (TextView) findViewById(R.id.check_in_anim);

        preImgBtn.setOnClickListener(this);
        nextImgBtn.setOnClickListener(this);
        signInImageView.setOnClickListener(this);
    }

    /**
     * 获取是否已签到数据,以及当前时间, 已签过日期
     */
    public void getCheckInData() {
    // 这里是请求数据库的值,没个公司,每个人要的数据是不一样的,到时候大家修改,大家编译的时候要对Activity好好修改,我是懒得改了
//      请求成功
            @Override
            public void onSuccess(ShowCheckInResult genericResult) {
                super.onSuccess(genericResult);
                if (genericResult.getCode() == GenericResult.SUCCESS) {

                    if (genericResult.getRulesText() != null) {
                        rules = genericResult.getRulesText();
                    }
                    invalidateOptionsMenu();

                    signInImageView.setVisibility(View.VISIBLE);
                    mCheckInUtils.setServerTime(genericResult.getServerTime());
                    viewpager(genericResult.getServerTime()); //当前月已签过days
                    currentLogs = genericResult.getLogs();
                    //今天已签过到
                    if (genericResult.isHasCheckIn()) {
                        signInImageView.setEnabled(false);
                        signInImageView.setImageResource(R.drawable.icon_checked_logtoday);
                        logTodayBgImageView.setImageResource(R.drawable.bg_logtoday_flower_open);
                    } else {
                        signInImageView.setEnabled(true);
                    }
                } else {
                    super.onFailure(genericResult);
                }
            }
        };
    }

    /**
     * 设置ViewPager数
     * @param serverTime
     */
    private void viewpager(long serverTime){
        CalendarView[] views = new CalendarView[3];
        for (int i = 0; i < 3; i++) {
            views[i] = new CalendarView(this, this, serverTime);
        }
        adapter = new CalendarViewAdapter<>(views);
        mShowViews = adapter.getAllItems();
        setViewPager();

        //(解决请求玩数据第一页不显示问题:没有对当前CalenderView执行onDraw方法,是因为CalenderView没有在UI线程)
        mViewPager.post(new Runnable() {
            @Override
            public void run() {
                mShowViews[0].setCurrentCheckInDays(currentLogs);
            }
        });
    }

    /**
     * 设置ViewPager其他特性
     */
    private void setViewPager() {
        mViewPager.setAdapter(adapter);
        mViewPager.setCurrentItem(498);
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                measureDirection(position);
                updateCalendarView(position);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
    }

    /**
     * 计算方向
     *
     * @param arg0
     */
    private void measureDirection(int arg0) {

        if (arg0 > mCurrentIndex) {
            mDirection = SildeDirection.RIGHT;

        } else if (arg0 < mCurrentIndex) {
            mDirection = SildeDirection.LEFT;
        }
        mCurrentIndex = arg0;
    }

    // 更新日历视图
    private void updateCalendarView(int arg0) {
        if (mDirection == SildeDirection.RIGHT) {
            mShowViews[arg0 % mShowViews.length].rightSlide();
        } else if (mDirection == SildeDirection.LEFT) {
            mShowViews[arg0 % mShowViews.length].leftSlide();
        }
        mDirection = SildeDirection.NO_SILDE;

    }


    /**
     * 月份切换
     * @param date
     */

    @Override
    public void changeDate(CustomDateModel date) {
        monthText.setText(date.getYear() + "-" + date.getMonth());
        getMonthLogs(date);
    }

    /**
     * 当前页面签到日期查询
     * @param date
     * @return
     */
    private void getMonthLogs(CustomDateModel date){
            //请求成功
            public void onSuccess(MonthSignLogModel genericResult) {
                super.onSuccess(genericResult);
                if (genericResult.getCode() == GenericResult.SUCCESS) {
                    if (genericResult.getLogs() != null) {
                        mShowViews[mViewPager.getCurrentItem() % mShowViews.length].setCheckInDays(genericResult.getLogs());
                    }
                } else {
                    super.onFailure(genericResult);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.last_month:
                mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1);
                break;
            case R.id.next_month:
                mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1);
                break;
            case R.id.log_today_check:
                if (mViewPager.getCurrentItem() != 498) {
                    if (currentLogs != null) {
                        mShowViews[mViewPager.getCurrentItem() % mShowViews.length].setCurrentCheckInDays(currentLogs);
                    } else {
                        mShowViews[mViewPager.getCurrentItem() % mShowViews.length].currentUpdate();
                    }
                    mShowViews[mViewPager.getCurrentItem() % mShowViews.length].SignIn();
                } else {
                        mShowViews[0].SignIn();
                }

                //请求成功
                    @Override
                    public void onSuccess(CheckInResult genericResult) {
                        super.onSuccess(genericResult);
                        if (genericResult.getCode() == GenericResult.SUCCESS) {//签到成功
                            setClickDate(genericResult);

                        } else {
                                confirmDialog.setConfirmContent(genericResult.getMessage());
                            }
                            confirmDialog.show();
                            confirmDialog.setRightButtonClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    confirmDialog.dismiss();
                                    startActivity(new Intent(CheckInActivity.this, MyCoupon.class));
                                }
                            });
                        } else {
                            super.onFailure(genericResult);
                        }
                    }
                });
                break;
        }
    }

    /**
     * 设置点击数据
     * @param genericResult
     */
    private void setClickDate(CheckInResult genericResult){

        if (genericResult.getCouponInfoModel() != null) {
            CouponInfoModel model = genericResult.getCouponInfoModel();
            couponRmb.setText("¥" + model.getAmount());
            couponArea.setText(model.getScopInfo());
        }
        if (mCheckInUtils.getCurrentTime().equals(monthText.getText()) && genericResult.getJingYan() > 0) {
            anim(genericResult.getJingYan());
        }
        signInImageView.setEnabled(false);
        signInImageView.setImageResource(R.drawable.icon_checked_logtoday);
        logTodayBgImageView.setImageResource(R.drawable.bg_logtoday_flower_open);
    }

    /**
     * 经验值增加动画
     */
    private void anim(int jinYan){

        animText.setText(getResources().getString(R.string.log_today_experience) + jinYan);
        animText.setVisibility(View.VISIBLE);
        AnimationSet set = new AnimationSet(false);
        TranslateAnimation translateAnimation = new TranslateAnimation(0.1f, 0.1f, 0.1f, -200f);
        translateAnimation.setDuration(2500);
        translateAnimation.setFillAfter(true);

        AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0);
        alphaAnimation.setDuration(1000);
        alphaAnimation.setFillAfter(true);
        set.addAnimation(alphaAnimation);
        set.addAnimation(translateAnimation);

        animText.setAnimation(set);
        set.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                animText.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (rules != null) {
            getMenuInflater().inflate(R.menu.menu_log_today, menu);
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.log_gift:
                if (checkInRuleDialog == null){
                    checkInRuleDialog = new CheckInRuleDialog(this);
                    if (rules != null){
                        checkInRuleDialog.setRulesText(rules);
                    }
                }
                checkInRuleDialog.show();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

}


5.XML :删除了很多跟公司资源相关的东西

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="oct.mama.activity.CheckInActivity">


        <RelativeLayout
            android:id="@+id/log_today_day"
            android:layout_below="@+id/log_today_istrue"
            android:layout_width="match_parent"
            android:layout_height="32dp"
            android:background="@color/log_today_calendar_bg"
            android:layout_marginRight="5dp"
            android:layout_marginLeft="5dp">
            <ImageView
                android:id="@+id/last_month"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:paddingTop="10dp"
                android:paddingBottom="5dp"
                android:paddingLeft="10dp"
                android:paddingRight="20dp"
                android:src="@drawable/icon_last_month" />
            <ImageView
                android:id="@+id/next_month"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_alignBottom="@+id/last_month"
                android:src="@drawable/icon_next_month"
                android:paddingTop="10dp"
                android:paddingBottom="5dp"
                android:paddingLeft="10dp"
                android:paddingRight="20dp" />
            <TextView
                android:id="@+id/log_today_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/common_white"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="15dp"/>
        </RelativeLayout>
        <TableLayout
            android:id="@+id/log_today_week"
            android:layout_below="@+id/log_today_day"
            android:layout_width="match_parent"
            android:layout_height="25dip"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:paddingBottom="5dp"
            android:background="@color/log_today_calendar_bg">
            <TableRow>
                <TextView
                    android:layout_width="0dp"
                    android:layout_height="fill_parent"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:textSize="15sp"
                    android:text="@string/sunday"
                    android:textColor="@color/common_white" />

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="fill_parent"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:textSize="15sp"
                    android:text="@string/monday"
                    android:textColor="@color/common_white" />
                <TextView
                    android:layout_width="0dp"
                    android:layout_height="fill_parent"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:textSize="15sp"
                    android:text="@string/thesday"
                    android:textColor="@color/common_white" />

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="fill_parent"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:textSize="15sp"
                    android:text="@string/wednesday"
                    android:textColor="@color/common_white" />

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="fill_parent"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:textSize="15sp"
                    android:text="@string/thursday"
                    android:textColor="@color/common_white" />

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="fill_parent"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:textSize="15sp"
                    android:text="@string/friday"
                    android:textColor="@color/common_white" />

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="fill_parent"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:textSize="15sp"
                    android:text="@string/saturday"
                    android:textColor="@color/common_white" />
            </TableRow>
        </TableLayout>
        <RelativeLayout
            android:id="@+id/vp_relative"
            android:layout_below="@+id/log_today_week"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <android.support.v4.view.ViewPager
                android:id="@+id/vp_calendar"
                android:layout_width="match_parent"
                android:layout_height="225dp"
                android:paddingTop="15dp"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="5dp"
                android:background="@color/log_today_calendar_bg"
                android:layout_gravity="center">
            </android.support.v4.view.ViewPager>
            <View
                android:layout_width="match_parent"
                android:layout_height="0.5dp"
                android:layout_marginRight="5dp"
                android:layout_marginLeft="5dp"
                android:background="@color/log_today_green_line"/>
            <TextView
                android:id="@+id/check_in_anim"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:textSize="16sp"
                android:visibility="gone"
                android:textColor="@color/log_today_experience_text"/>
        </RelativeLayout>
        <ImageView
            android:id="@+id/log_today_check"
            android:layout_below="@+id/vp_relative"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:src="@drawable/btn_log_today_selector"
            android:layout_marginTop="20dp"
            android:layout_marginBottom="20dp"
            android:visibility="gone"/>
    </RelativeLayout>

</LinearLayout>


在此,感谢zou128865,没有看他的博客我不可能很快就做出自己的东西,上面代码是编译通不过的缺少了一下资源文件,我也没有办法贴出来,大家拿到代码认真的分析分析加上自己的资源就能跑了。

推荐阅读:
  1. HTML5 自定义日历控件
  2. 日历控件

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

标签 日历 android

上一篇:jQuery.Validate表单验证校验-说明

下一篇:GT手机性能测试工具二:项目中配置

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》