自定义日历控件

Android自定义日历控件(继承系统控件实现)

主要步骤

  1. 编写布局
  2. 继承LinearLayout设置子控件
  3. 设置数据
  4. 继承TextView实现有圆圈背景的TextView
  5. 添加Attribute
  6. 添加长按事件

1.编写布局

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

    <RelativeLayout
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="30dp">

        <ImageView
            android:id="@+id/btn_pre"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:src="@mipmap/ic_launcher" />

        <ImageView
            android:id="@+id/btn_next"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:src="@mipmap/ic_launcher" />

        <TextView
            android:id="@+id/txtData"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:text="@string/app_name" />

    </RelativeLayout>

    <LinearLayout
        android:id="@+id/week_header"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="1" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="2" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="3" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="4" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="5" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="6" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="7" />
    </LinearLayout>

    <GridView
        android:id="@+id/grid"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="7" />

</LinearLayout>

2.继承LinearLayout设置子控件

public class CalendarView extends LinearLayout {
    private ImageView btnPre;
    private ImageView btnNext;
    private TextView txtData;
    private GridView gridView;
    private Calendar calendar = Calendar.getInstance();
    private String displayFormat;
    public NewViewListener viewListener;

    public void setViewListener(NewViewListener viewListener) {
        this.viewListener = viewListener;
    }

    public CalendarView(Context context) {
        super(context);
    }

    public CalendarView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initControl(context, attrs);
    }

    public CalendarView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initControl(context, attrs);
    }

    private void initControl(Context context, AttributeSet attributeSet) {
        bindControl(context);
        bindControlEvent();
        setAttribute(attributeSet);
        renderCalender();
    }

    private void bindControl(Context context) {
        LayoutInflater.from(context).inflate(R.layout.new_view, this);
        btnNext = (ImageView) findViewById(R.id.btn_next);
        btnPre = (ImageView) findViewById(R.id.btn_pre);
        txtData = (TextView) findViewById(R.id.txtData);
        gridView = (GridView) findViewById(R.id.grid);
    }

    private void bindControlEvent() {
        btnNext.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                calendar.add(Calendar.MONTH, +1);
                renderCalender();
            }
        });
        btnPre.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                calendar.add(Calendar.MONTH, -1);
                renderCalender();
            }
        });
    }
 }

3.设置数据

private void renderCalender() {

        //返回"月+日"格式的数据
        SimpleDateFormat sdf = new SimpleDateFormat(displayFormat, Locale.CHINA);
        txtData.setText(sdf.format(calendar.getTime()));

        ArrayList<Date> cells = new ArrayList<>();

        Calendar calendar2 = (Calendar) this.calendar.clone();
        //设置月的第一天为1
        calendar2.set(Calendar.DAY_OF_MONTH, 1);

        //获取当前周数的前一天
        int prevDays = calendar2.get(Calendar.DAY_OF_WEEK) - 1;
        //运算日历加上加前一周
        calendar2.add(Calendar.DAY_OF_MONTH, -prevDays);

        int maxCellCount = 6 * 7;

        //将日历里的日期数据添加到ArrayList
        while (cells.size() < maxCellCount) {
            cells.add(calendar2.getTime());
            calendar2.add(Calendar.DAY_OF_MONTH, 1);
        }

        gridView.setAdapter(new MyAdapter(getContext(), cells));
        gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (viewListener == null) {
                    return false;
                } else {
                    viewListener.onItemLongPress((Date) parent.getItemAtPosition(position));
                    return true;
                }
            }
        });
    }

    private class MyAdapter extends ArrayAdapter<Date> {

        LayoutInflater layoutInflater;

        MyAdapter(@NonNull Context context, ArrayList<Date> dates) {
            super(context, R.layout.calendar_text_day, dates);
            layoutInflater = LayoutInflater.from(context);
        }

        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            Date date = getItem(position);
            if (convertView == null) {
                convertView = layoutInflater.inflate(R.layout.calendar_text_day, parent, false);
            }
            int day = date.getDate();
            ((CalendarTextView) convertView).setText(String.valueOf(day));
            Date now = new Date();

            boolean isSameMonth = false;
            if (date.getMonth() == now.getMonth()) {
                isSameMonth = true;
            }

            if (isSameMonth) {
                ((CalendarTextView) convertView).setTextColor(Color.DKGRAY);
            }

            if (now.getDate() == date.getDate() && now.getMonth() == date.getMonth() && now.getYear() == date.getYear()) {
                ((CalendarTextView) convertView).setNow(true);
            }
            return convertView;
        }
    }

4. 圆圈背景TextView

public class CalendarTextView extends AppCompatTextView {
    private Paint paint;
    private boolean isNow = false;

    public void setNow(boolean now) {
        isNow = now;
    }

    public CalendarTextView(Context context) {
        super(context);
    }

    public CalendarTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initControl();
    }

    public CalendarTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initControl();
    }


    private void initControl() {
        paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.RED);
        paint.setStrokeWidth(2);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (isNow) {
            canvas.translate(getWidth() / 2, getHeight() / 2);
            canvas.drawCircle(0, 0, getWidth() / 2, paint);
            setTextColor(Color.RED);
        }
    }
}

5.添加Attribute

  1. 添加attrs文件

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <declare-styleable name="CalendarView">
            <attr name="dateFormat" format="string" />
        </declare-styleable>
    </resources>
    
  2. 将Arrtibute参数设置到控件

    private void setAttribute(AttributeSet attributeSet) {
        TypedArray ta = getContext().obtainStyledAttributes(attributeSet, R.styleable.CalendarView);
        try {
            displayFormat = ta.getString(R.styleable.CalendarView_dateFormat);
            if (displayFormat == null) {
                displayFormat = "MMM yyy";
            }
        } finally {
            ta.recycle();
        }
    }
    
  3. 在布局中加入命名空间引入

    <com.example.jiyang.newview.CalendarView xmlns:CalendarView="http://schemas.android.com/apk/res/com.example.jiyang.newview"
        android:id="@+id/newView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="10dp"
        CalendarView:dateFormat="MMMM yyyy" />
    

6.添加长按事件

  1. 定义长按接口

    public interface NewViewListener {
        void onItemLongPress(Date day);
    }
    
  2. CalenderView中调用

gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (viewListener == null) {
return false;
} else {
viewListener.onItemLongPress((Date) parent.getItemAtPosition(position));
return true;
}
}
});
```

  1. Activity中实现接口方法

@Override
public void onItemLongPress(Date day) {
DateFormat df = SimpleDateFormat.getDateInstance();
Toast.makeText(this, df.format(day), Toast.LENGTH_SHORT).show();
}
```

总结

  • Attribute的使用

    1. 定义attrs文件
    2. 注意命名空间。自定义View不能使用app:,而要使用xmlns:自定义一个命名空间
    3. TypedArray放入try{}finaly{}中,要在finally中释放TypedArray typedArray.recycle()
  • 通过继承布局实现自定义View时,加载布局
    需要LayoutInflater.from(context).inflate(R.layout.new_view, this);不能LayoutInflater.from(context).inflate(R.layout.new_view, this,false);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容