Android自定义时间线控件

效果图

时间线控件

初步思路

自定义控件是必须的,看效果首先想到的就是继承LinearLayout
View的排布,LinearLayout已经帮我们搞定了,我们需要做的就是把左边的时间线和状态圆点给画出来。
至于绘画的状态又有两种,一种是普通状态,一种是高亮状态。这时候我们可以提供当前View的位置信息,抽象出接口,把状态的选择权让给用户。
时间点:通过对应的View的getY() + getHeight()/2就可以获取对应的时间点位置。
时间线:我们只需要记录第一个View和最后一个View对应的时间点位置就可以画出来了

小细节

绘图的过程中有许多细节需要去注意

  • 自定义ViewGroup控件必须提供背景色,否则不会调用onDraw()方法
  • 画点跟画线的顺序必须是先画线,再画点,否则点上面就会被线给遮盖部分。

代码实现

TimeLineView.java

package demo.august1996.top.timelineviewdemo.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;

/**
 * Created by August on 16/8/20.
 */
public class TimeLineView extends LinearLayout {

    //高亮图片
    private Bitmap mIcon;

    //时间线左右边距
    private int leftAndRightMargin = dp2px(30);

    //第一个点的坐标
    private int firstX;
    private int firstY;


    //最后一个点的坐标
    private int lastX;
    private int lastY;

    //时间线画笔、颜色、粗细
    private Paint linePaint;
    private int lineColor = Color.parseColor("#ff4ed6b4");
    private int lineStoke = dp2px(2);

    //时间点画笔
    private Paint pointPaint;
    private int pointColor = Color.parseColor("#ff4ed6b4");
    private int pointRadius = dp2px(5);


    //提供当前位置是否为高亮状态
    private HeightLineProvider mHeightLineProvider;

    public interface HeightLineProvider {
        boolean isHeightLine(int position);
    }

    public TimeLineView(Context context) {
        this(context, null);

    }

    public TimeLineView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TimeLineView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        prePare();
    }

    /**
     * 初始化
     */
    private void prePare() {
        linePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        linePaint.setColor(lineColor);
        linePaint.setStrokeWidth(lineStoke);
        linePaint.setStyle(Paint.Style.FILL);


        pointPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        pointPaint.setColor(pointColor);
        pointPaint.setDither(true);
        pointPaint.setStyle(Paint.Style.FILL);
        setOrientation(VERTICAL);
    }


    /**
     * 设置供用户选择是否高亮的接口
     *
     * @param provider
     */
    public void setHeightLineProvider(HeightLineProvider provider) {
        this.mHeightLineProvider = provider;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawTimeLine(canvas);
    }

    /**
     * 绘画时间线
     *
     * @param canvas
     */
    private void drawTimeLine(Canvas canvas) {
        //没有子View,不用绘画
        if (getChildCount() == 0)
            return;

        //计算起点和终点位置,并且画出所有点
        countFirstPoint();
        countLastPoint();
        drawJoinLine(canvas);
        drawPoint(canvas);
    }

    /**
     * 计算起点位置
     */
    private void countFirstPoint() {
        firstX = leftAndRightMargin;
        View view = getChildAt(0);
        firstY = (int) (view.getY() + view.getHeight() / 2);
    }

    /**
     * 计算终点位置
     */
    private void countLastPoint() {
        lastX = leftAndRightMargin;
        View lastView = getChildAt(getChildCount() - 1);
        lastY = (int) (lastView.getY() + lastView.getHeight() / 2);
    }

    /**
     * 画线
     * @param canvas
     */
    private void drawJoinLine(Canvas canvas) {
        countLastPoint();
        canvas.drawLine(firstX, firstY, lastX, lastY, linePaint);
    }

    /**
     * 画出点
     * @param canvas
     */
    private void drawPoint(Canvas canvas) {

        for (int i = 0; i < getChildCount(); i++) {
            int x = leftAndRightMargin;
            View view = getChildAt(i);
            int y = (int) (view.getY() + view.getHeight() / 2);
            /**
             * 如果用户设置了选择状态的权利并且返回真并且设置了高亮图片,则画出高亮状态,否则画出正常状态
             */
            if (mHeightLineProvider != null && mHeightLineProvider.isHeightLine(i) && mIcon != null) {
                drawHeightLine(canvas, x, y);
            } else {
                drawNorPoint(canvas, x, y);
            }
        }
    }


    /**
     * 画正常点
     * @param canvas
     * @param x
     * @param y
     */
    private void drawNorPoint(Canvas canvas, int x, int y) {
        canvas.drawCircle(x, y, pointRadius, pointPaint);
    }

    /**
     * 画出高亮点
     * @param canvas
     * @param x
     * @param y
     */
    private void drawHeightLine(Canvas canvas, int x, int y) {
        canvas.drawBitmap(mIcon, x - mIcon.getWidth() / 2, y - mIcon.getHeight() / 2, null);
    }

    /**
     * dp转px
     * @param dp
     * @return
     */
    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getContext().getResources().getDisplayMetrics());
    }

    /**
     * 设置高亮点的图片
     * @param bitmap
     */
    public void setHeightBitmap(Bitmap bitmap) {
        this.mIcon = bitmap;
    }
}

item_test.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="20dp"
    android:paddingLeft="60dp"
    android:paddingRight="15dp"
    android:paddingBottom="20dp">

    <TextView
        android:id="@+id/tx_action"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        android:textColor="#1a1a1a"
        android:text="测试一"/>

    <TextView
        android:id="@+id/tx_action_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="12sp"
        android:textColor="#8e8e8e"
        android:layout_below="@id/tx_action"
        android:layout_marginTop="10dp"
        android:text="2015-07-12 20:34:34"/>

    <TextView
        android:id="@+id/tx_action_status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        android:textColor="#3dd1a5"
        android:layout_alignParentRight="true"
        android:text="完成"/>

</RelativeLayout>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="addView"
            android:text="addView" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="removeView"
            android:text="removeView" />
    </LinearLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <demo.august1996.top.timelineviewdemo.widget.TimeLineView
            android:id="@+id/tlv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#fff"></demo.august1996.top.timelineviewdemo.widget.TimeLineView>
    </ScrollView>

</LinearLayout>

MainActivity.java

package demo.august1996.top.timelineviewdemo;

import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

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

import demo.august1996.top.timelineviewdemo.widget.TimeLineView;

public class MainActivity extends AppCompatActivity implements TimeLineView.HeightLineProvider {

    @Override
    public boolean isHeightLine(int position) {
        if (position % 4 == 0) {
            return true;
        }
        return false;
    }

    private TimeLineView tlv;
    private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tlv = (TimeLineView) findViewById(R.id.tlv);
        tlv.setHeightLineProvider(this);
        BitmapDrawable bitmapDrawable = (BitmapDrawable) getResources().getDrawable(R.drawable.ic_ok);
        tlv.setHeightBitmap(bitmapDrawable.getBitmap());

    }

    private void addItem() {
        View v = LayoutInflater.from(this).inflate(R.layout.item_test, tlv, false);
        ((TextView) v.findViewById(R.id.tx_action)).setText(tlv.getChildCount() + "探访了你");
        ((TextView) v.findViewById(R.id.tx_action_time)).setText(sdf.format(new Date()));
        ((TextView) v.findViewById(R.id.tx_action_status)).setText("查看");
        tlv.addView(v);
    }

    public void addView(View v) {
        addItem();
    }

    public void removeView(View v) {
        if (tlv.getChildCount() != 0) {
            tlv.removeViewAt(tlv.getChildCount() - 1);
        }
    }
}

源码

Github源码

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

推荐阅读更多精彩内容