2014年8月15日 星期五

如何画出一张日历 android

http://www.apkbus.com/android-18453-1-1.html

首先,在主界面自定义一个类Grid01
    <view
        class="cn.prs.component.Grid01"
        android:cacheColorHint="#EFEFEF"
        android:layout_width="fill_parent"
        android:layout_height="300dip"
        android:background="#EFEFEF"
        android:id="@+id/view01" />
然后继承View,定义各种参数,
1public class Grid01 extends View {
    /*
     * 整个页面的宽高
     */
    private int width, height, bound, length;
    /*
     * 页面显示的年月日
     */
    private int month, year, day;
    /*
     * 定义画笔
     */
    public Paint mPaint;
    /*
     *阳历日期
     */
    public String[][] array;
    /*
     * 1900年1月31日=阴历0年1月1日
     */
public String[][] array1;
public static String[] weeks = { "周一", "周二", "周三", "周四", "周五", "周六", "周日" };  
2、初始化画笔
    /*
     * 使用布局文件时用
     */
    public Grid01(Context context, AttributeSet attrs) {
       super(context, attrs);
       /*
        * 初始化画笔
        */
       initBrush();
    }
    private void initBrush() {
       // TODO Auto-generated method stub
       mPaint = new Paint(); // 初始化画笔
       mPaint.setStrokeWidth(0);// 调线条宽
       mPaint.setTextSize(16);// 设置字体大小
       mPaint.setTextAlign(Paint.Align.CENTER);// 设置文字放置位置
       mPaint.setTypeface(Typeface.create("隶书", Typeface.BOLD));
}
3、获取阴阳历数组
    private void initArray() {
       // TODO Auto-generated method stub
       MA ma = new MA (year, month);
       array = ma.getArray();
       this.setArray(array);
       array1 = ma.getArray1();
       this.setArray1(array1);
}
4、实现其内部方法
@Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
       this.width = w;
       this.height = h;
       super.onSizeChanged(w, h, oldw, oldh);
    }
5、画图
    @Override
    protected void onDraw(Canvas canvas) {
       super.onDraw(canvas);
       /*
        * 要六行,七列
        */
       length = width / 7 + 1;// 横长
       bound = height / 7 + 1;// 竖长
       // 横竖线
       for (int i = 0; i < 7; i++) {
           // text, x, y, paint
           mPaint.setColor(Color.BLACK);// 设置背景
           canvas.drawText(weeks, i * length + 25, 20, mPaint);
}
6、画数据,继续
       for (int i = 0; i < 6; i++) {
           /*
            * 画桌布
            */
           for (int j = 0; j < 7; j++) {
              String text = array[j];
              String text1 = array1[j];
           /*
               * 填充日期数据
               */
              canvas.drawText(text, j * length , i * bound + bound
                     / 2, mPaint);
canvas.drawText(text1, j * length , i * bound  + bound/ 2, mPaint);
              /*
               * 把画笔颜色重新设为黑色
               */
              mPaint.setColor(Color.BLACK);// 设置背景
}
}
7、使用view.invalidate();刷新数据
效果图如下
 

沒有留言:

張貼留言