建立自己的王國:Android 自定義封裝View-4(下)

(上一篇)http://www.itdecent.cn/p/2b9bdd5c2949介紹了怎么畫星期名。
這部介紹畫月的天數(shù)。

別爾蓋茨語錄

思路:

1.獲得今天的日期,畫對應的日期名字下。
2.計算出當前日期左邊右邊的值,并畫出
3.處理一些特殊情況,比如計算的天數(shù)不在當前月,兩位數(shù)和一位數(shù)的位置等
**4.按照距離關系,設定點擊事件。

實現(xiàn):

老規(guī)矩,重寫View的構造方法以及onMeasure,onDraw方法, 為了點擊事件重寫onTouch方法.
1.定義需要的變量。

/**
     * M paint
     */
    private lateinit var mPaint: Paint
    private lateinit var cPaint: Paint
    /**
     * Current 當前天
     */
    private var current: Int? = null
    /**
     * Today 當前日期
     */
    private var today: Int by Delegates.notNull()
    /**
     * Start 開始數(shù)字
     */
    private var start: Int? = null
    /**
     * Month 當前月
     */
    private var month: Int by Delegates.notNull()
    /**
      *本年
      */
    private var year by Delegates.notNull<Int>()
    /**
     * Last month max 上月總天數(shù)
     */
    private var lastMonthMax by Delegates.notNull<Int>()
    /**
     * Current month max  本月總天數(shù)
     */
    private var currentMonthMax by Delegates.notNull<Int>()
      /**
      *負責點擊事件的處理。
    **/
   
  1. 為了處理點擊事件,添加接口
/**
 * Add on date click listener
 * 點擊事件
 * @constructor Create empty Add on date click listener
 */
interface AddOnDateClickListener {
    fun singleClick(position: Int)
}
  1. 初始化變量。
    private fun initView() {
        //獲取今天的數(shù)據(jù)
        val calendar = Calendar.getInstance()
        //時區(qū)
        calendar.timeZone = TimeZone.getTimeZone("GMT+8")
        year = calendar.get(Calendar.YEAR)
        //注:月從0開始的。
        month = calendar.get(Calendar.MONTH) + 1
        //今天
        today = calendar.get(Calendar.DAY_OF_MONTH)
        //周數(shù)

        if (current == null) {
            //注意:開始是從周日
            current =if (calendar.get(Calendar.DAY_OF_WEEK)==7){
                0
            }else{
                calendar.get(Calendar.DAY_OF_WEEK)-1
            }

        }
        //比較周,然后計算出開始日期.
        if (start == null) {
            start=today- current!! +1

        }
        //獲取上個月的天數(shù)。
        //如果不再本年。
        with(month - 1) {
            lastMonthMax = if (this == 0) {
                //12月的總數(shù)永遠是31天,所以不需要從Calendar獲取。
                31
            } else {
                getMonthLastDay(year, this)
            }
        }
        //獲取本月最大天數(shù).
        currentMonthMax = getMonthLastDay(year, month)

        mPaint = Paint()
        mPaint.textSize = DisplayUtils.dip2px(14F).toFloat()
        mPaint.color = Color.parseColor("#3E3E3F")
        mPaint.isAntiAlias = true

        cPaint = Paint()
        cPaint.color = Color.parseColor("#005BAB")
        cPaint.isAntiAlias = true

    }
  1. 重寫onMeasure方法,并且進行Padding值的運算
    //寫死寬度,高度最少37dp并且添加左右Padding值。
        setMeasuredDimension(
            widthMeasureSpec,
            (DisplayUtils.dip2px(37F) + DisplayUtils.dip2Px(paddingBottom+paddingTop)).toInt()
        )

5.重寫onDraw方法

 //index (索引) 0...6, value (值) -1...6(取決于當前的日期)
        for ((index, value: Int) in (start!!..start!! + 6).withIndex()) {
            mPaint.color = Color.parseColor("#3E3E3F")
            //要畫的數(shù)字(天數(shù),可能是上月的,也可能是下個月的。)
            var tempPrintValue = value
            //如果是當天,畫圓形,畫天數(shù)文字。
            if (current!! - 1 == index) {
                //判斷
                //如果低于本月。
                if (value <= 0) {
                    tempPrintValue = lastMonthMax + value
                }
                //如果超過本月
                if (value > currentMonthMax) {
                    tempPrintValue = value - currentMonthMax
                }
                mPaint.color = Color.WHITE
                //畫園。
                canvas?.drawCircle(
                    (index * width) / 7F + DisplayUtils.dip2px(
                        if (tempPrintValue > 9) {
                            31F
                        } else {
                            27F
                        }
                    ),
                    ((height/2).toFloat()),
                    DisplayUtils.dip2px(12F).toFloat(),
                    cPaint
                )
                //描繪天數(shù).
                canvas?.drawText(
                    tempPrintValue.toString(),
                    (index * width) / 7F + DisplayUtils.dip2px(
                        if (index.toString().length > 1) {
                            18F
                        } else {
                            23F
                        }
                    ),
                    (height/2)+DisplayUtils.dip2Px(5),mPaint
                )

            } else {
                //判斷
                //如果低于本月。
                if (value <= 0) {
                    tempPrintValue = lastMonthMax + value
                    mPaint.color = Color.parseColor("#7E7E7E")
                }
                //如果超過本月
                if (value > currentMonthMax) {
                    tempPrintValue = value - currentMonthMax
                    mPaint.color = Color.parseColor("#7E7E7E")
                }
                //描繪天數(shù).
                canvas?.drawText(
                    tempPrintValue.toString(),
                    (index * width) / 7F + DisplayUtils.dip2px(
                        if (tempPrintValue.toString().length > 1) {
                            18F
                        } else {
                            23F
                        }
                    ),
                    (height/2)+DisplayUtils.dip2Px(5),
                   // DisplayUtils.dip2px(24F).toFloat(),
                    mPaint
                )
            }
        }
        canvas?.save()

注:onDraw里面處理了一位數(shù)和兩位數(shù)的時候的圓形的位置。
6.點擊事件的處理。
主要思路:把寬度等7分,然后不同的區(qū)域給對應的值。
更改當前選定的日期,并且重繪,高亮。

 /**
     * 點擊事件的處理。
     */
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        val x = event!!.x
//注意:只處理點(down),不處理up,move等,
        if (event.action == MotionEvent.ACTION_DOWN) {
            when (x.toInt()) {
                in 0..width / 7 -> {
                    this.singleClick(1)
                    current = 1
                }
                in width * 1 / 7..width * 2 / 7 -> {
                    this.singleClick(2)
                    current = 2
                }
                in width * 2 / 7..width * 3 / 7 -> {
                    this.singleClick(3)
                    current = 3
                }
                in width * 3 / 7..width * 4 / 7 -> {
                    this.singleClick(4)
                    current = 4
                }
                in width * 4 / 7..width * 5 / 7 -> {
                    this.singleClick(5)
                    current = 5
                }
                in width * 5 / 7..width * 6 / 7 -> {
                    this.singleClick(6)
                    current = 6
                }
                in width * 6 / 7..width -> {
                    this.singleClick(7)
                    current = 7
                }
            }
          //參數(shù)重新初始化。
            initView()
          //重繪
            postInvalidate()
        }
        return true
    }
  1. 使用的Utils。
 /**
     * 得到指定月的天數(shù)
     */
    private fun getMonthLastDay(year: Int, month: Int): Int {
        val a = Calendar.getInstance()
        a[Calendar.YEAR] = year
        a[Calendar.MONTH] = month - 1
        a[Calendar.DATE] = 1 //把日期設置為當月第一天
        a.roll(Calendar.DATE, -1) //日期回滾一天,也就是最后一天
        return a[Calendar.DATE]
    }

  /**
     * dp轉px
     *
     * @param dipValue
     * @return
     */
    fun dip2px(dipValue: Float): Int {
        val scale: Float = Resources.getSystem().displayMetrics.density
        return (dipValue * scale + 0.5f).toInt()
    }

    /**
     *點擊事件的處理。
   **/
    override fun singleClick(position: Int) {
        Toast.makeText(context,"選中${start!!+position-1}", Toast.LENGTH_LONG).show()
    }

最后跟上一篇的星期名結合。


Screenshot_20210920_035304.png
Screenshot_20210920_035309.png

完美,收工。

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容