Android 自定义View :时间轴
前言
- Android开发中,时间轴的 UI需求非常常见,如下图:
- 本文将结合 自定义View & RecyclerView的知识,手把手教你实现该常见 & 实用的自定义View:时间轴
目录
1. 知识储备
本文采用 自定义View & RecyclerView 实现时间轴,所以必须先了解相关知识:
1.1 RecyclerView
-
RecyclerView 的基础使用:Android开发:ListView、AdapterView、RecyclerView全面解析
-
RecyclerView 的高级使用:教你玩转 Android RecyclerView:深入解析 RecyclerView.ItemDecoration类(含实例讲解)
1.2 自定义View
具体请看文章 Canvas类的最全面详解 - 自定义View应用系列
2. 具体实现
下面,将手把手教你实现 时光轴的效果。
2.1 效果图
2.2 实现思路
2.3 实现步骤
- 导入 使用 RecyclerView的包
- 设置主布局 & RecyclerView的Item布局
- 设置RecyclerView的 Adapter
- 自定义RecyclerView.ItemDecoration类
- 初始化 RecyclerView & 绑定数据
特别注意
- 步骤1、2、3、5都用到RecyclerView的基本知识,请看文章Android开发:ListView、AdapterView、RecyclerView全面解析
- 步骤 4 涉及到RecyclerView 高级使用 & 自定义View的知识,具体请看Canvas类的最全面详解 - 自定义View应用系列 & 教你玩转 Android RecyclerView:深入解析 RecyclerView.ItemDecoration类(含实例讲解)
2.4 步骤说明
步骤1:导入 使用 RecyclerView的包
build.gradle
dependencies {
...
implementation 'com.android.support:recyclerview-v7:23.2.0'
}
androidx 如下即可
implementation 'com.google.android.material:material:1.2.1'
步骤2:设置主布局 & RecyclerView的Item布局
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:设置RecyclerView的 Adapter
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter {
private LayoutInflater inflater;
private ArrayList<HashMap<String, Object>> listItem;
//构造函数,传入数据
public MyAdapter(Context context, ArrayList<HashMap<String, Object>> listItem) {
inflater = LayoutInflater.from(context);
this.listItem = listItem;
}