Android 自定義View實(shí)戰(zhàn) :時(shí)間軸


前言

  • Android開發(fā)中,時(shí)間軸的 UI需求非常常見,如下圖:

    示意圖

  • 本文將結(jié)合 自定義View & RecyclerView的知識(shí),手把手教你實(shí)現(xiàn)該常見 & 實(shí)用的自定義View:時(shí)間軸


目錄

目錄

1. 知識(shí)儲(chǔ)備

本文采用 自定義View & RecyclerView 實(shí)現(xiàn)時(shí)間軸,所以必須先了解相關(guān)知識(shí):

1.1 RecyclerView

1.2 自定義View

具體請(qǐng)看文章 Canvas類的最全面詳解 - 自定義View應(yīng)用系列


2. 具體實(shí)現(xiàn)

下面,我將手把手教你實(shí)現(xiàn) 時(shí)光軸的效果。

2.1 效果圖

示意圖

2.2 實(shí)現(xiàn)思路

示意圖

2.3 實(shí)現(xiàn)步驟

  1. 導(dǎo)入 使用 RecyclerView的包
  2. 設(shè)置主布局 & RecyclerViewItem布局
  3. 設(shè)置RecyclerViewAdapter
  4. 自定義RecyclerView.ItemDecoration
  5. 初始化 RecyclerView & 綁定數(shù)據(jù)

特別注意

  1. 步驟1、2、3、5都用到RecyclerView的基本知識(shí),請(qǐng)看文章Android開發(fā):ListView、AdapterView、RecyclerView全面解析
  2. 步驟 4 涉及到RecyclerView 高級(jí)使用 & 自定義View的知識(shí),具體請(qǐng)看Canvas類的最全面詳解 - 自定義View應(yīng)用系列 & 教你玩轉(zhuǎn) Android RecyclerView:深入解析 RecyclerView.ItemDecoration類(含實(shí)例講解)

2.4 步驟說明

** 步驟1:導(dǎo)入 使用 RecyclerView的包**

build.gradle

dependencies {
    ...
    compile 'com.android.support:recyclerview-v7:23.2.0'
}

步驟2:設(shè)置主布局 & RecyclerViewItem布局
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context="${relativePackage}.${activityClass}" >

    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="horizontal"
        />
</RelativeLayout>

list_cell.xml

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

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="New Text"
            android:id="@+id/Itemtitle" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="New Text"
            android:textSize="10sp"
            android:id="@+id/Itemtext"
            android:layout_below="@+id/Itemtitle"/>

</LinearLayout>

步驟3:設(shè)置RecyclerViewAdapter
MyAdapter.java

public class MyAdapter extends RecyclerView.Adapter {
    private LayoutInflater inflater;
    private ArrayList<HashMap<String, Object>> listItem;

    //構(gòu)造函數(shù),傳入數(shù)據(jù)
    public MyAdapter(Context context, ArrayList<HashMap<String, Object>> listItem) {
        inflater = LayoutInflater.from(context);
        this.listItem = listItem;
    }


    //定義Viewholder
    class Viewholder extends RecyclerView.ViewHolder  {
        private TextView Title, Text;

        public Viewholder(View root) {
            super(root);
            Title = (TextView) root.findViewById(R.id.Itemtitle);
            Text = (TextView) root.findViewById(R.id.Itemtext);

        }

        public TextView getTitle() {
            return Title;
        }

        public TextView getText() {
            return Text;
        }


    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new Viewholder(inflater.inflate(R.layout.list_cell, null));
    }//在這里把ViewHolder綁定Item的布局

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        Viewholder vh = (Viewholder) holder;
        // 綁定數(shù)據(jù)到ViewHolder里面
        vh.Title.setText((String) listItem.get(position).get("ItemTitle"));
        vh.Text.setText((String) listItem.get(position).get("ItemText"));
    }

    //返回Item數(shù)目
    @Override
    public int getItemCount() {
        return listItem.size();
    }


}

步驟4:自定義RecyclerView.ItemDecoration

  • 此步驟就是該實(shí)例的實(shí)現(xiàn)關(guān)鍵,具體思路請(qǐng)看下圖:
示意圖

閱讀前請(qǐng)先看文章教你玩轉(zhuǎn) Android RecyclerView:深入解析 RecyclerView.ItemDecoration類(含實(shí)例講解)

  • 具體代碼實(shí)現(xiàn)

DividerItemDecoration.java

public class DividerItemDecoration extends RecyclerView.ItemDecoration {

    // 寫右邊字的畫筆(具體信息)
    private Paint mPaint;

    // 寫左邊日期字的畫筆( 時(shí)間 + 日期)
    private Paint mPaint1;
    private Paint mPaint2;

    // 左 上偏移長(zhǎng)度
    private int itemView_leftinterval;
    private int itemView_topinterval;

    // 軸點(diǎn)半徑
    private int circle_radius;

    // 圖標(biāo)
    private Bitmap mIcon;


    // 在構(gòu)造函數(shù)里進(jìn)行繪制的初始化,如畫筆屬性設(shè)置等
    public DividerItemDecoration(Context context) {

        // 軸點(diǎn)畫筆(紅色)
        mPaint = new Paint();
        mPaint.setColor(Color.RED);

        // 左邊時(shí)間文本畫筆(藍(lán)色)
        // 此處設(shè)置了兩只分別設(shè)置 時(shí)分 & 年月
        mPaint1 = new Paint();
        mPaint1.setColor(Color.BLUE);
        mPaint1.setTextSize(30);

        mPaint2 = new Paint();
        mPaint2.setColor(Color.BLUE);


        // 賦值ItemView的左偏移長(zhǎng)度為200
        itemView_leftinterval = 200;

        // 賦值ItemView的上偏移長(zhǎng)度為50
        itemView_topinterval = 50;

        // 賦值軸點(diǎn)圓的半徑為10
        circle_radius = 10;

        // 獲取圖標(biāo)資源
        // mIcon = BitmapFactory.decodeResource(context.getResources(), R.mipmap.logo);

    }

    // 重寫getItemOffsets()方法
    // 作用:設(shè)置ItemView 左 & 上偏移長(zhǎng)度
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);

            // 設(shè)置ItemView的左 & 上偏移長(zhǎng)度分別為200 px & 50px,即此為onDraw()可繪制的區(qū)域
            outRect.set(itemView_leftinterval, itemView_topinterval, 0, 0);

    }

    // 重寫onDraw()
    // 作用:在間隔區(qū)域里繪制時(shí)光軸線 & 時(shí)間文本
    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);

        // 獲取RecyclerView的Child view的個(gè)數(shù)
        int childCount = parent.getChildCount();

        // 遍歷每個(gè)Item,分別獲取它們的位置信息,然后再繪制對(duì)應(yīng)的分割線
        for (int i = 0; i < childCount; i++) {

            // 獲取每個(gè)Item對(duì)象
            View child = parent.getChildAt(i);

            /**
             * 繪制軸點(diǎn)
             */
            // 軸點(diǎn) = 圓 = 圓心(x,y)
            float centerx = child.getLeft() - itemView_leftinterval / 3;
            float centery = child.getTop() - itemView_topinterval + (itemView_topinterval + child.getHeight()) / 2;
            // 繪制軸點(diǎn)圓
            c.drawCircle(centerx, centery, circle_radius, mPaint);
            // 通過Canvas繪制角標(biāo)
            // c.drawBitmap(mIcon,centerx - circle_radius ,centery - circle_radius,mPaint);

            /**
             * 繪制上半軸線
             */
            // 上端點(diǎn)坐標(biāo)(x,y)
            float upLine_up_x = centerx;
            float upLine_up_y = child.getTop() - itemView_topinterval;

            // 下端點(diǎn)坐標(biāo)(x,y)
            float upLine_bottom_x = centerx;
            float upLine_bottom_y = centery - circle_radius;

            //繪制上半部軸線
            c.drawLine(upLine_up_x, upLine_up_y, upLine_bottom_x, upLine_bottom_y, mPaint);

            /**
             * 繪制下半軸線
             */
            // 上端點(diǎn)坐標(biāo)(x,y)
            float bottomLine_up_x = centerx;
            float bottom_up_y = centery + circle_radius;

            // 下端點(diǎn)坐標(biāo)(x,y)
            float bottomLine_bottom_x = centerx;
            float bottomLine_bottom_y = child.getBottom();

            //繪制下半部軸線
            c.drawLine(bottomLine_up_x, bottom_up_y, bottomLine_bottom_x, bottomLine_bottom_y, mPaint);


            /**
             * 繪制左邊時(shí)間文本
             */
            // 獲取每個(gè)Item的位置
            int index = parent.getChildAdapterPosition(child);
            // 設(shè)置文本起始坐標(biāo)
            float Text_x = child.getLeft() - itemView_leftinterval * 5 / 6;
            float Text_y = upLine_bottom_y;

            // 根據(jù)Item位置設(shè)置時(shí)間文本
            switch (index) {
                case (0):
                    // 設(shè)置日期繪制位置
                    c.drawText("13:40", Text_x, Text_y, mPaint1);
                    c.drawText("2017.4.03", Text_x + 5, Text_y + 20, mPaint2);
                    break;
                case (1):
                    // 設(shè)置日期繪制位置
                    c.drawText("17:33", Text_x, Text_y, mPaint1);
                    c.drawText("2017.4.03", Text_x + 5, Text_y + 20, mPaint2);
                    break;
                case (2):
                    // 設(shè)置日期繪制位置
                    c.drawText("20:13", Text_x, Text_y, mPaint1);
                    c.drawText("2017.4.03", Text_x + 5, Text_y + 20, mPaint2);
                    break;
                case (3):
                    // 設(shè)置日期繪制位置
                    c.drawText("11:40", Text_x, Text_y, mPaint1);
                    c.drawText("2017.4.04", Text_x + 5, Text_y + 20, mPaint2);
                    break;
                case (4):
                    // 設(shè)置日期繪制位置
                    c.drawText("13:20", Text_x, Text_y, mPaint1);
                    c.drawText("2017.4.04", Text_x + 5, Text_y + 20, mPaint2);
                    break;
                case (5):
                    // 設(shè)置日期繪制位置
                    c.drawText("22:40", Text_x, Text_y, mPaint1);
                    c.drawText("2017.4.04", Text_x + 5, Text_y + 20, mPaint2);
                    break;
                default:c.drawText("已簽收", Text_x, Text_y, mPaint1);
            }
        }
    }

}

** 步驟5:初始化RecyclerView & 綁定數(shù)據(jù) **

MainActivity.java

public class MainActivity extends AppCompatActivity  {
    private RecyclerView Rv;
    private ArrayList<HashMap<String,Object>> listItem;
    private MyAdapter myAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化顯示的數(shù)據(jù)
        initData();

        // 綁定數(shù)據(jù)到RecyclerView
        initView();

    }
    // 初始化顯示的數(shù)據(jù)
    public void initData(){
        listItem = new ArrayList<HashMap<String, Object>>();/*在數(shù)組中存放數(shù)據(jù)*/

            HashMap<String, Object> map1 = new HashMap<String, Object>();
            HashMap<String, Object> map2 = new HashMap<String, Object>();
            HashMap<String, Object> map3 = new HashMap<String, Object>();
            HashMap<String, Object> map4 = new HashMap<String, Object>();
            HashMap<String, Object> map5 = new HashMap<String, Object>();
            HashMap<String, Object> map6 = new HashMap<String, Object>();

            map1.put("ItemTitle", "美國(guó)谷歌公司已發(fā)出");
            map1.put("ItemText", "發(fā)件人:谷歌 CEO Sundar Pichai");
            listItem.add(map1);

            map2.put("ItemTitle", "國(guó)際順豐已收入");
            map2.put("ItemText", "等待中轉(zhuǎn)");
            listItem.add(map2);

            map3.put("ItemTitle", "國(guó)際順豐轉(zhuǎn)件中");
            map3.put("ItemText", "下一站中國(guó)");
            listItem.add(map3);

            map4.put("ItemTitle", "中國(guó)順豐已收入");
            map4.put("ItemText", "下一站廣州華南理工大學(xué)");
            listItem.add(map4);

            map5.put("ItemTitle", "中國(guó)順豐派件中");
            map5.put("ItemText", "等待派件");
            listItem.add(map5);

            map6.put("ItemTitle", "華南理工大學(xué)已簽收");
            map6.put("ItemText", "收件人:Carson");
            listItem.add(map6);
    }

    // 綁定數(shù)據(jù)到RecyclerView
    public void initView(){
        Rv = (RecyclerView) findViewById(R.id.my_recycler_view);
        //使用線性布局
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        Rv.setLayoutManager(layoutManager);
        Rv.setHasFixedSize(true);

        //用自定義分割線類設(shè)置分割線
        Rv.addItemDecoration(new DividerItemDecoration(this));

        //為L(zhǎng)istView綁定適配器
        myAdapter = new MyAdapter(this,listItem);
        Rv.setAdapter(myAdapter);
    }

}

2.5 結(jié)果展示

示意圖

2.6 源碼地址

Carson_Ho的Github地址:自定義View實(shí)踐 - 時(shí)間軸

希望大家動(dòng)動(dòng)手指給個(gè) Star 唄, 嘻嘻!


3. 擴(kuò)展使用

  • 此次的擴(kuò)展使用是為了更加豐富UI效果:將軸點(diǎn)圓圈改成圖標(biāo),如下圖:
示意圖
  • 代碼實(shí)現(xiàn)
      private Bitmap mIcon;

      // 獲取圖標(biāo)資源
         mIcon = BitmapFactory.decodeResource(context.getResources(), R.mipmap.logo);

     // 在步驟4中,繪制軸點(diǎn)圓圈處 通過Canvas繪制該圖
     c.drawBitmap(mIcon,centerx - circle_radius ,centery - circle_radius,mPaint);

4. 總結(jié)


歡迎關(guān)注Carson_Ho的簡(jiǎn)書

不定期分享關(guān)于安卓開發(fā)的干貨,追求短、平、快,但卻不缺深度


請(qǐng)點(diǎn)贊!因?yàn)槟愕墓膭?lì)是我寫作的最大動(dòng)力!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,837評(píng)論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,196評(píng)論 3 414
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,688評(píng)論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,654評(píng)論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,456評(píng)論 6 406
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 54,955評(píng)論 1 321
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,044評(píng)論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,195評(píng)論 0 287
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,725評(píng)論 1 333
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,608評(píng)論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,802評(píng)論 1 369
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,318評(píng)論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,048評(píng)論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,422評(píng)論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,673評(píng)論 1 281
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,424評(píng)論 3 390
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,762評(píng)論 2 372

推薦閱讀更多精彩內(nèi)容