Android时间轴控件-WheelView

2024-02-07 04:50

本文主要是介绍Android时间轴控件-WheelView,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在做时间轴或者某些类型的选择时,有时候设计师会给我们出类似下面的效果:
在这里插入图片描述
因此,我们就需要重新自定义scrollview,,也就是移动端常用的时间轴控件:WheelView

实现方式直接上代码:

public class WheelView extends ScrollView {public static final String TAG = WheelView.class.getSimpleName();public static class OnWheelViewListener {public void onSelected(int selectedIndex, String item) {}}private Context context;
//    private ScrollView scrollView;private LinearLayout views;public WheelView(Context context) {super(context);init(context);}public WheelView(Context context, AttributeSet attrs) {super(context, attrs);init(context);}public WheelView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);init(context);}//    String[] items;List<String> items;private List<String> getItems() {return items;}public void setItems(List<String> list) {if (null == items) {items = new ArrayList<String>();}items.clear();items.addAll(list);// 前面和后面补全for (int i = 0; i < offset; i++) {items.add(0, "");items.add("");}initData();}// 每页显示的数量public static final int OFF_SET_DEFAULT = 1;int offset = OFF_SET_DEFAULT; // 偏移量(需要在最前面和最后面补全)int displayItemCount;int selectedIndex = 1; //int itemHeight = 0;//每个条目的高度int textSize = 20;//每个条目的字体大小public int getOffset() {return offset;}public void setOffset(int offset) {this.offset = offset;}public void setTextSize(int textSize) {this.textSize = textSize;}private void init(Context context) {this.context = context;//        scrollView = ((ScrollView)this.getParent());
//        Log.d(TAG, "scrollview: " + scrollView);Log.d(TAG, "parent: " + this.getParent());
//        this.setOrientation(VERTICAL);this.setVerticalScrollBarEnabled(false);views = new LinearLayout(context);views.setOrientation(LinearLayout.VERTICAL);this.addView(views);scrollerTask = new Runnable() {public void run() {int newY = getScrollY();if (initialY - newY == 0) { // stoppedfinal int remainder = initialY % itemHeight;final int divided = initialY / itemHeight;
//                    Log.d(TAG, "initialY: " + initialY);
//                    Log.d(TAG, "remainder: " + remainder + ", divided: " + divided);if (remainder == 0) {selectedIndex = divided + offset;onSeletedCallBack();} else {if (remainder > itemHeight / 2) {WheelView.this.post(new Runnable() {@Overridepublic void run() {WheelView.this.smoothScrollTo(0, initialY - remainder + itemHeight);selectedIndex = divided + offset + 1;onSeletedCallBack();}});} else {WheelView.this.post(new Runnable() {@Overridepublic void run() {WheelView.this.smoothScrollTo(0, initialY - remainder);selectedIndex = divided + offset;onSeletedCallBack();}});}}} else {initialY = getScrollY();WheelView.this.postDelayed(scrollerTask, newCheck);}}};}int initialY;Runnable scrollerTask;int newCheck = 50;public void startScrollerTask() {initialY = getScrollY();this.postDelayed(scrollerTask, newCheck);}private void initData() {displayItemCount = offset * 2 + 1;for (String item : items) {views.addView(createView(item));}refreshItemView(0);}private TextView createView(String item) {TextView tv = new TextView(context);tv.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));tv.setSingleLine(true);tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);tv.setText(item);tv.setGravity(Gravity.CENTER);int padding = dip2px(15);tv.setPadding(padding, padding, padding, padding);if (0 == itemHeight) {itemHeight = getViewMeasuredHeight(tv);Log.d(TAG, "itemHeight: " + itemHeight);views.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, itemHeight * displayItemCount));LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) this.getLayoutParams();this.setLayoutParams(new LinearLayout.LayoutParams(lp.width, itemHeight * displayItemCount));}return tv;}@Overrideprotected void onScrollChanged(int l, int t, int oldl, int oldt) {super.onScrollChanged(l, t, oldl, oldt);//        Log.d(TAG, "l: " + l + ", t: " + t + ", oldl: " + oldl + ", oldt: " + oldt);//        try {
//            Field field = ScrollView.class.getDeclaredField("mScroller");
//            field.setAccessible(true);
//            OverScroller mScroller = (OverScroller) field.get(this);
//
//
//            if(mScroller.isFinished()){
//                Log.d(TAG, "isFinished...");
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }refreshItemView(t);if (t > oldt) {
//            Log.d(TAG, "向下滚动");scrollDirection = SCROLL_DIRECTION_DOWN;} else {
//            Log.d(TAG, "向上滚动");scrollDirection = SCROLL_DIRECTION_UP;}}private void refreshItemView(int y) {int position = y / itemHeight + offset;int remainder = y % itemHeight;int divided = y / itemHeight;if (remainder == 0) {position = divided + offset;} else {if (remainder > itemHeight / 2) {position = divided + offset + 1;}//            if(remainder > itemHeight / 2){
//                if(scrollDirection == SCROLL_DIRECTION_DOWN){
//                    position = divided + offset;
//                    Log.d(TAG, ">down...position: " + position);
//                }else if(scrollDirection == SCROLL_DIRECTION_UP){
//                    position = divided + offset + 1;
//                    Log.d(TAG, ">up...position: " + position);
//                }
//            }else{position = y / itemHeight + offset;
//                if(scrollDirection == SCROLL_DIRECTION_DOWN){
//                    position = divided + offset;
//                    Log.d(TAG, "<down...position: " + position);
//                }else if(scrollDirection == SCROLL_DIRECTION_UP){
//                    position = divided + offset + 1;
//                    Log.d(TAG, "<up...position: " + position);
//                }
//            }
//        }//        if(scrollDirection == SCROLL_DIRECTION_DOWN){
//            position = divided + offset;
//        }else if(scrollDirection == SCROLL_DIRECTION_UP){
//            position = divided + offset + 1;}int childSize = views.getChildCount();for (int i = 0; i < childSize; i++) {TextView itemView = (TextView) views.getChildAt(i);if (null == itemView) {return;}if (position == i) {itemView.setTextColor(checkTextColor);} else {itemView.setTextColor(nocheckTextColor);}}}int checkTextColor = Color.parseColor("#0288ce");int nocheckTextColor = Color.parseColor("#bbbbbb");//设置选中的字体颜色public void setCheckTextColor(String checkTextColor) {this.checkTextColor = Color.parseColor(checkTextColor);}public void setCheckTextColor(int checkTextColor) {this.checkTextColor = checkTextColor;}//设置未选中的字体颜色public void setNocheckTextColor(String nocheckTextColor) {this.nocheckTextColor = Color.parseColor(nocheckTextColor);}public void setNocheckTextColor(int nocheckTextColor) {this.nocheckTextColor = nocheckTextColor;}/*** 获取选中区域的边界*/int[] selectedAreaBorder;private int[] obtainSelectedAreaBorder() {if (null == selectedAreaBorder) {selectedAreaBorder = new int[2];selectedAreaBorder[0] = itemHeight * offset;selectedAreaBorder[1] = itemHeight * (offset + 1);}return selectedAreaBorder;}private int scrollDirection = -1;private static final int SCROLL_DIRECTION_UP = 0;private static final int SCROLL_DIRECTION_DOWN = 1;Paint paint;int viewWidth;@Overridepublic void setBackgroundDrawable(Drawable background) {if (viewWidth == 0) {viewWidth = ((Activity) context).getWindowManager().getDefaultDisplay().getWidth();Log.d(TAG, "viewWidth: " + viewWidth);}if (null == paint) {paint = new Paint();paint.setColor(Color.parseColor("#83cde6"));paint.setStrokeWidth(dip2px(1f));}background = new Drawable() {@Overridepublic void draw(Canvas canvas) {canvas.drawLine(viewWidth * 1 / 6, obtainSelectedAreaBorder()[0], viewWidth * 5 / 6, obtainSelectedAreaBorder()[0], paint);canvas.drawLine(viewWidth * 1 / 6, obtainSelectedAreaBorder()[1], viewWidth * 5 / 6, obtainSelectedAreaBorder()[1], paint);}@Overridepublic void setAlpha(int alpha) {}@Overridepublic void setColorFilter(ColorFilter cf) {}@SuppressLint("WrongConstant")@Overridepublic int getOpacity() {return 0;}};super.setBackgroundDrawable(background);}@Overrideprotected void onSizeChanged(int w, int h, int oldw, int oldh) {super.onSizeChanged(w, h, oldw, oldh);Log.d(TAG, "w: " + w + ", h: " + h + ", oldw: " + oldw + ", oldh: " + oldh);viewWidth = w;setBackgroundDrawable(null);}/*** 选中回调*/private void onSeletedCallBack() {if (null != onWheelViewListener) {onWheelViewListener.onSelected(selectedIndex, items.get(selectedIndex));}}public void setSeletion(int position) {final int p = position;selectedIndex = p + offset;this.post(new Runnable() {@Overridepublic void run() {WheelView.this.smoothScrollTo(0, p * itemHeight);}});}public String getSeletedItem() {return items.get(selectedIndex);}public int getSeletedIndex() {return selectedIndex - offset;}@Overridepublic void fling(int velocityY) {super.fling(velocityY / 3);}@Overridepublic boolean onTouchEvent(MotionEvent ev) {if (ev.getAction() == MotionEvent.ACTION_UP) {startScrollerTask();}return super.onTouchEvent(ev);}private OnWheelViewListener onWheelViewListener;public OnWheelViewListener getOnWheelViewListener() {return onWheelViewListener;}public void setOnWheelViewListener(OnWheelViewListener onWheelViewListener) {this.onWheelViewListener = onWheelViewListener;}private int dip2px(float dpValue) {final float scale = context.getResources().getDisplayMetrics().density;return (int) (dpValue * scale + 0.5f);}private int getViewMeasuredHeight(View view) {int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);int expandSpec = View.MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, View.MeasureSpec.AT_MOST);view.measure(width, expandSpec);return view.getMeasuredHeight();}}

外面设置属性和传数据的使用方式如下:

val layout_wheelview = findViewById<WheelView>(R.id.layout_wheelview).apply {//设置选中的字体颜色setCheckTextColor(Color.BLACK)//设置条目字体大小setTextSize(18)//设置列表数据setItems(listContent)//添加滑动监听onWheelViewListener = object : WheelView.OnWheelViewListener() {override fun onSelected(selectedIndex: Int, item: String) {}}}

外面获取当前选中的条目:

layout_wheelview.seletedIndex

这篇关于Android时间轴控件-WheelView的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/686563

相关文章

C#实现WinForm控件焦点的获取与失去

《C#实现WinForm控件焦点的获取与失去》在一个数据输入表单中,当用户从一个文本框切换到另一个文本框时,需要准确地判断焦点的转移,以便进行数据验证、提示信息显示等操作,本文将探讨Winform控件... 目录前言获取焦点改变TabIndex属性值调用Focus方法失去焦点总结最后前言在一个数据输入表单

基于Qt Qml实现时间轴组件

《基于QtQml实现时间轴组件》时间轴组件是现代用户界面中常见的元素,用于按时间顺序展示事件,本文主要为大家详细介绍了如何使用Qml实现一个简单的时间轴组件,需要的可以参考下... 目录写在前面效果图组件概述实现细节1. 组件结构2. 属性定义3. 数据模型4. 事件项的添加和排序5. 事件项的渲染如何使用

Android数据库Room的实际使用过程总结

《Android数据库Room的实际使用过程总结》这篇文章主要给大家介绍了关于Android数据库Room的实际使用过程,详细介绍了如何创建实体类、数据访问对象(DAO)和数据库抽象类,需要的朋友可以... 目录前言一、Room的基本使用1.项目配置2.创建实体类(Entity)3.创建数据访问对象(DAO

Android WebView的加载超时处理方案

《AndroidWebView的加载超时处理方案》在Android开发中,WebView是一个常用的组件,用于在应用中嵌入网页,然而,当网络状况不佳或页面加载过慢时,用户可能会遇到加载超时的问题,本... 目录引言一、WebView加载超时的原因二、加载超时处理方案1. 使用Handler和Timer进行超

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

Android平台播放RTSP流的几种方案探究(VLC VS ExoPlayer VS SmartPlayer)

技术背景 好多开发者需要遴选Android平台RTSP直播播放器的时候,不知道如何选的好,本文针对常用的方案,做个大概的说明: 1. 使用VLC for Android VLC Media Player(VLC多媒体播放器),最初命名为VideoLAN客户端,是VideoLAN品牌产品,是VideoLAN计划的多媒体播放器。它支持众多音频与视频解码器及文件格式,并支持DVD影音光盘,VCD影

android-opencv-jni

//------------------start opencv--------------------@Override public void onResume(){ super.onResume(); //通过OpenCV引擎服务加载并初始化OpenCV类库,所谓OpenCV引擎服务即是 //OpenCV_2.4.3.2_Manager_2.4_*.apk程序包,存

从状态管理到性能优化:全面解析 Android Compose

文章目录 引言一、Android Compose基本概念1.1 什么是Android Compose?1.2 Compose的优势1.3 如何在项目中使用Compose 二、Compose中的状态管理2.1 状态管理的重要性2.2 Compose中的状态和数据流2.3 使用State和MutableState处理状态2.4 通过ViewModel进行状态管理 三、Compose中的列表和滚动

Android 10.0 mtk平板camera2横屏预览旋转90度横屏拍照图片旋转90度功能实现

1.前言 在10.0的系统rom定制化开发中,在进行一些平板等默认横屏的设备开发的过程中,需要在进入camera2的 时候,默认预览图像也是需要横屏显示的,在上一篇已经实现了横屏预览功能,然后发现横屏预览后,拍照保存的图片 依然是竖屏的,所以说同样需要将图片也保存为横屏图标了,所以就需要看下mtk的camera2的相关横屏保存图片功能, 如何实现实现横屏保存图片功能 如图所示: 2.mtk

android应用中res目录说明

Android应用的res目录是一个特殊的项目,该项目里存放了Android应用所用的全部资源,包括图片、字符串、颜色、尺寸、样式等,类似于web开发中的public目录,js、css、image、style。。。。 Android按照约定,将不同的资源放在不同的文件夹中,这样可以方便的让AAPT(即Android Asset Packaging Tool , 在SDK的build-tools目