自定義日曆控件-——Android

    

    這幾天公司出了簽到的需求,讓我來做簽到這一塊,剛開始以爲非常好做,不就是調用系統的日曆嗎。系統的日曆與簽到標籤基於足夠完成了。我首先用Android5.0以上的機器調用了日曆控件,發現還不錯,但是用了一臺4.2的機器調用日曆。我靠!這醜不拉幾,看着都要吐了還能用?沒有辦法,我只能嘗試自定義日曆控件了。

    下面是設計給的我第一張圖:

                  wKioL1ZJrpawvJAgAABvCUVztl8565.png

剛開始我想的是可以畫爲6行7列的網格,GridView可以實現,正準備做,可是下午設計又給了我一張圖:

                  wKioL1ZJr5PQ11T3AABxQw63Ciw023.png

    大白圈是今天的日期,小白點是這個月已簽過到的日期,黑色字體是已經過去的日期,灰色是還沒有到來的日期。這變化有點大啊,這要的話用GridView就得區分好幾種不同的Type了,如果以後還有其他加的不是會更麻煩,然後只能自己畫View這樣,自己對這個View很熟悉,以後要添加什麼功能可以很清楚的加上代碼。

    於是我就在網上搜Android自定義日曆控件,當我在CSDN上看到zou128865寫的Android UI-自定義日曆控件正好能滿足我目前的需求,於是我就把他的代碼下載下來,仔細的研究。在他的代碼上修改變成我自己的日曆控件。好啦廢話不多說了,開始我們的日曆控件之旅吧。 


        當我要做完這個控件的時候,設計發來了最終稿的動態圖:不能上傳完整的動態不然老闆搞死我,見諒哈。

            wKiom1ZJvYyT87g4AAEh3iaJNDM937.png

不會上傳動態圖呀 !!!!!!

    來開始代碼:

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,沒有看他的博客我不可能很快就做出自己的東西,上面代碼是編譯通不過的缺少了一下資源文件,我也沒有辦法貼出來,大家拿到代碼認真的分析分析加上自己的資源就能跑了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章