Android 自定义横向时间轴

示例:

一、添加依赖

dependencies {
    ***
    ***
    //添加RecyclerView的依赖包
    implementation 'androidx.recyclerview:recyclerview:1.2.1'
}

二、页面代码

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:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">



    <!--时间轴列表-->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="wrap_content"
        android:layout_height="70dp" />

</LinearLayout>

list_point_cell.xml:

<?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:gravity="center"
    android:orientation="vertical">

   <TextView
       android:id="@+id/item_time"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_marginLeft="10dp"
       android:layout_marginRight="10dp"
       android:text="time"
       android:textSize="12sp" />

  <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="30dp"
      android:orientation="horizontal">
      <ImageView
          android:id="@+id/item_start_img"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_weight="1"
          android:scaleType="fitXY"
          android:src="@mipmap/ic_line"/>

      <ImageView
          android:id="@+id/item_point_img"
          android:layout_width="15dp"
          android:layout_height="match_parent"
          android:src="@mipmap/ic_unselected_circle"/>

      <ImageView
          android:id="@+id/item_end_img"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_weight="1"
          android:scaleType="fitXY"
          android:src="@mipmap/ic_line"/>

  </LinearLayout>

    <TextView
        android:id="@+id/item_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:text="text"
        android:textSize="12sp" />
</LinearLayout>

三、java代码

MyRecyclerAdapter.java适配器

package com.example.horiztimeaxis;

import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.HashMap;
import java.util.List;

import static android.content.Context.MODE_PRIVATE;

public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.MyViewHolder>  {

    private OnItemClickListener itemClickListener;// 接口对象
    private Context context;// 上下文
    private List<HashMap<String,String>> itemList;// 数据集合
    private int lastIndex = -1;

    public MyRecyclerAdapter(Context context,List<HashMap<String,String>> itemList){
        super();
        this.context = context;
        this.itemList = itemList;
        lastIndex = itemList.size()-1;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // TODO 自动生成的方法存根
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.list_point_cell,null);
        MyViewHolder holder = new MyViewHolder(view);
        return holder;

    }


    @Override
    public void onBindViewHolder(MyViewHolder holder,int position) {
        // 设置未选中状态
        holder.item_point_img.setImageDrawable(context.getDrawable(R.mipmap.ic_unselected_circle));
        holder.item_start_img.setVisibility(View.VISIBLE);
        holder.item_end_img.setVisibility(View.VISIBLE);
        // 隐藏第一个
        if (position==0){
            holder.item_start_img.setVisibility(View.INVISIBLE);
        }
        // 隐藏最后一个
        if (position == lastIndex){
            holder.item_end_img.setVisibility(View.INVISIBLE);
        }

        SharedPreferences time_sp = context.getSharedPreferences("TIME_LINE_SP",MODE_PRIVATE);
        int index = time_sp.getInt("INDEX_TIME",-1);
        if (index==position){
            // 设置选中状态
            holder.item_point_img.setImageDrawable(context.getDrawable(R.mipmap.ic_selected_circle));
        }

        HashMap<String, String> hashMap = itemList.get(position);
        // 赋值
        holder.time.setText(hashMap.get("TIME"));
        holder.tv.setText(hashMap.get("TEXT"));


    }

    @Override
    public int getItemCount() {
        return itemList.size();
    }


    protected class MyViewHolder extends RecyclerView.ViewHolder {
        private TextView time;
        private ImageView item_start_img;
        private ImageView item_point_img;
        private ImageView item_end_img;
        private TextView tv;
        /**
         * @param itemView
         */
        public MyViewHolder(View itemView) {
            super(itemView);
            time = itemView.findViewById(R.id.item_time);
            item_start_img = itemView.findViewById(R.id.item_start_img);
            item_point_img = itemView.findViewById(R.id.item_point_img);
            item_end_img = itemView.findViewById(R.id.item_end_img);
            tv = itemView.findViewById(R.id.item_text);

            // 设置点击事件
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    itemClickListener.onItemClick(getAbsoluteAdapterPosition());
                }
            });
        }
    }


    /**
     * 点击接口方法(监听)
     * */
    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    /**
     * 回调函数
     * */
    public void ItemClickCallBack(OnItemClickListener itemClickListener){
        this.itemClickListener = itemClickListener;
    }

}
MainActivity.java
package com.example.horiztimeaxis;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    private RecyclerView rv;
    private MyRecyclerAdapter adapter;
    // 时间轴中数据
    private ArrayList<HashMap<String,String>> listItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
    }

    /**
     * 使用方法
     * */
    private void init(){
        // 数据初始化
        initData();
        /** ---时间轴--- **/
        rv = findViewById(R.id.rv);

        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        // 竖向布局
        //linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        // 横向布局
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        // 设置布局
        rv.setLayoutManager(linearLayoutManager);
        // 设置adpater
        adapter = new MyRecyclerAdapter(this,listItem);
        adapter.ItemClickCallBack(new MyRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                SharedPreferences time_sp = getSharedPreferences("TIME_LINE_SP",MODE_PRIVATE);
                SharedPreferences.Editor editor = time_sp.edit();
                editor.putInt("INDEX_TIME",position);
                editor.commit();
                // 刷新
                adapter.notifyDataSetChanged();

                // 选中内容
                HashMap<String, String> map = listItem.get(position);
                Toast.makeText(getApplicationContext(),map.get("TIME")+map.get("TEXT"),Toast.LENGTH_SHORT).show();
            }
        });
        rv.setAdapter(adapter);

    }


    // 初始化显示的数据
    private void initData(){
        /*在数组中存放数据*/
        listItem = new ArrayList<HashMap<String, String>>();

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

        map1.put("TIME", "2023-8-3");
        map1.put("TEXT", "土地尚未开工");
        listItem.add(map1);

        map2.put("TIME", "2023-8-27");
        map2.put("TEXT", "夯实地基");
        listItem.add(map2);

        map3.put("TIME", "2023-9-4");
        map3.put("TEXT", "浇筑地梁");
        listItem.add(map3);

        map4.put("TIME", "2023-9-20");
        map4.put("TEXT", "主体砌筑");
        listItem.add(map4);

        map5.put("TIME", "2023-10-9");
        map5.put("TEXT", "封顶");
        listItem.add(map5);

        map6.put("TIME", "2023-11-10");
        map6.put("TEXT", "内部装修");
        listItem.add(map6);
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你可以通过自定义布局和绘制来实现一个横向时间轴。以下是一个简单的示例: 1. 创建一个自定义的视图类,继承自 View。 ```java public class TimelineView extends View { private List<String> events; // 存储时间轴上的事件列表 public TimelineView(Context context) { super(context); init(); } public TimelineView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public TimelineView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { events = new ArrayList<>(); // 初始化事件列表 events.add("事件1"); events.add("事件2"); events.add("事件3"); // ... } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int width = getWidth(); int height = getHeight(); // 绘制时间轴的线 Paint linePaint = new Paint(); linePaint.setColor(Color.RED); linePaint.setStrokeWidth(5); canvas.drawLine(0, height / 2, width, height / 2, linePaint); // 绘制时间轴上的事件 Paint textPaint = new Paint(); textPaint.setColor(Color.BLACK); textPaint.setTextSize(30); int eventCount = events.size(); int eventSpacing = width / (eventCount + 1); // 事件之间的间距 for (int i = 0; i < eventCount; i++) { float xPos = eventSpacing * (i + 1); float yPos = height / 2; canvas.drawText(events.get(i), xPos, yPos, textPaint); } } } ``` 2. 在你的布局文件中使用自定义的 TimelineView。 ```xml <com.example.timeline.TimelineView android:layout_width="match_parent" android:layout_height="100dp" /> ``` 请注意,上述代码只是一个基本示例,你可以根据自己的需求进行扩展和美化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值