自定义颜色、大小渐变的圆点指示器

2024-08-31 23:18

本文主要是介绍自定义颜色、大小渐变的圆点指示器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!


源码 点击打开链接

首先看布局文件activity_main.xml

布局很简单只有装图片的ViewPager--以及自定义的圆点指示器

<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"tools:context="com.example.pageindicator.MainActivity" ><android.support.v4.view.ViewPagerandroid:id="@+id/mViewpager"android:layout_width="match_parent"android:layout_height="300dp" ></android.support.v4.view.ViewPager><com.example.pageindicator.CustomPageIndicatorandroid:id="@+id/mPagerIndicator"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center_horizontal"android:layout_marginTop="50dp" ></com.example.pageindicator.CustomPageIndicator></LinearLayout>

首先看主界面把MainActivity

package com.example.pageindicator;  import java.util.ArrayList;import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;public class MainActivity extends Activity {  private ViewPager mViewPager;  CustomPageIndicator mPagerIndicator;MyAdapter mAdapter;  private ArrayList<ImageView> imageViewList;  private boolean isScrolling = false;@SuppressWarnings("deprecation")  @Override  protected void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.activity_main);  imageViewList = new ArrayList<ImageView>();  int[] imagesInt = {R.drawable.p1,R.drawable.p2,R.drawable.p3};  for (int i = 0; i < imagesInt.length; i++) {  ImageView imageView = new ImageView(MainActivity.this);  imageView.setBackgroundResource(imagesInt[i]);  imageViewList.add(imageView);  }  mPagerIndicator = (CustomPageIndicator) findViewById(R.id.mPagerIndicator);mViewPager = (ViewPager) findViewById(R.id.mViewpager);  mAdapter = new MyAdapter();  mViewPager.setAdapter(mAdapter);  mViewPager.setOnPageChangeListener(new OnPageChangeListener() {  @Override  public void onPageSelected(int position) {  mPagerIndicator.setActivityCircle(position);}  @Override  public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {float percent = positionOffset;if(isScrolling && percent > 0.0f && percent < 1.0f){mPagerIndicator.setScrollProgress(position,percent);}}  @Override  public void onPageScrollStateChanged(int arg0) {if(arg0 != 0){isScrolling = true;}else{isScrolling = false;}//下面判断不严谨
//            	if(arg0 == 1){
//        			isScrolling = true;
//        		}else{
//        			isScrolling = false;
//        		}}  });  }  class MyAdapter extends PagerAdapter{  @Override  public int getCount() {  return imageViewList.size();  }  @Override  public boolean isViewFromObject(View arg0, Object arg1) {  return arg0 == arg1;  }  @Override  public void destroyItem(ViewGroup container, int position, Object object) {  container.removeView(imageViewList.get(position));  }  @Override  public Object instantiateItem(ViewGroup container, int position) {  container.addView(imageViewList.get(position));  return imageViewList.get(position);  }  }  
}  

主界面是最简单的ViewPager页面切换效果--主要是看    mPagerIndicator.setScrollProgress(position,percent);、mPagerIndicator.setActivityCircle(position);的代码

接下来就看圆点指示器自定义类把CustomPageIndicator 先贴出代码来,然后在稍微讲解下

package com.example.pageindicator;import java.util.ArrayList;import android.R.color;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.provider.CalendarContract.Colors;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;public class CustomPageIndicator extends View {int[] imagesInt = { R.drawable.p1, R.drawable.p2, R.drawable.p3 };private int circleCount = imagesInt.length;private int activeCircleIndex = 0;private int circleRadius;// 半径4private int activeCircleRadius;// 当前小球半径6private int circleDivider;// 间距6private ArrayList<Circle> circles = null;Paint mPaint;private int normalCircleColor;private int acitiveCircleColor;public CustomPageIndicator(Context context, AttributeSet attrs) {this(context, attrs, 0);}public CustomPageIndicator(Context context) {this(context, null);}public CustomPageIndicator(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);initCircle();}private void initCircle() {normalCircleColor = Color.parseColor("#000000");acitiveCircleColor = Color.parseColor("#EE3B3B");// 填充、抗锯齿--颜色、大小mPaint = new Paint();mPaint.setStyle(Paint.Style.FILL);mPaint.setAntiAlias(true);circleRadius = PhoneUtils.dp2px(getContext(), 4);activeCircleRadius = PhoneUtils.dp2px(getContext(), 6);circleDivider = PhoneUtils.dp2px(getContext(), 6);circles = new ArrayList<CustomPageIndicator.Circle>();// 创建3个原点集合for (int i = 0; i < circleCount; i++) {Circle circle = new Circle();if (activeCircleIndex == i) {// 当前的点位circle.color = acitiveCircleColor;circle.radius = activeCircleRadius;circle.centerX = activeCircleRadius;circle.centerY = activeCircleRadius;} else {// 其他点位circle.color = normalCircleColor;circle.radius = circleRadius;circle.centerX = activeCircleRadius + i* PhoneUtils.dp2px(getContext(), 14);circle.centerY = activeCircleRadius;}circles.add(circle);}}/*** 设置目前活动的小球* 第一部分根据startValue求出其中A,R,G,B中各个色彩的初始值;第二部分根据endValue求出其中A,R,G,B中各个色彩的结束值* ,最后是根据当前动画的百分比进度求出对应的数值*/public void setActivityCircle(int index) {lastCircle = circles.get(activeCircleIndex);lastCircle.color = ColorHelper.evaluate(0.1f, normalCircleColor,acitiveCircleColor);lastCircle.radius = circleRadius;activeCircleIndex = index;currentActivedCircele = circles.get(activeCircleIndex);currentActivedCircele.color = ColorHelper.evaluate(0.1f,acitiveCircleColor, normalCircleColor);currentActivedCircele.radius = activeCircleRadius;invalidate();}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {int resultWidth = 0;int resultHeight = 0;resultWidth = circleCount * circleRadius * 2 + (circleCount - 1)* circleDivider + 2 * (activeCircleRadius - circleRadius);resultHeight = 2 * activeCircleRadius;setMeasuredDimension(resultWidth, resultHeight);}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);for (int i = 0; i < circleCount; i++) {Circle circle = circles.get(i);mPaint.setColor(circle.color);canvas.drawCircle(circle.centerX, circle.centerY, circle.radius,mPaint);}}/*** 圆心xy坐标,半径,颜色*/private class Circle {float centerX;float centerY;float radius;int color;}private float lastPercent = -1;private Circle lastCircle;private Circle currentActivedCircele;private Circle right;private Circle left;public void setScrollProgress(int leftPosition, float percent) {right = circles.get(leftPosition + 1);left = circles.get(leftPosition);// 手指右滑-递减if (lastPercent > percent) {left.radius = circleRadius + (1 - percent)* PhoneUtils.dp2px(getContext(), 2);right.radius = circleRadius + percent* PhoneUtils.dp2px(getContext(), 2);if (left.color == normalCircleColor) {left.color = ColorHelper.evaluate(percent, normalCircleColor,acitiveCircleColor);} else {left.color = ColorHelper.evaluate(percent, acitiveCircleColor,normalCircleColor);}if (right.color == normalCircleColor) {right.color = ColorHelper.evaluate(1 - percent,normalCircleColor, acitiveCircleColor);} else {right.color = ColorHelper.evaluate(1 - percent,acitiveCircleColor, normalCircleColor);}}// 手指左滑-递增if (lastPercent < percent) {left.radius = circleRadius + (1 - percent)* PhoneUtils.dp2px(getContext(), 2);right.radius = circleRadius + percent* PhoneUtils.dp2px(getContext(), 2);if (right.color == normalCircleColor) {right.color = ColorHelper.evaluate(1 - percent,normalCircleColor, acitiveCircleColor);} else {right.color = ColorHelper.evaluate(1 - percent,acitiveCircleColor, normalCircleColor);}if (left.color == normalCircleColor) {left.color = ColorHelper.evaluate(percent, normalCircleColor,acitiveCircleColor);} else {left.color = ColorHelper.evaluate(percent, acitiveCircleColor,normalCircleColor);}}invalidate();lastPercent = percent;}}


上面的initCircle方法中是进行原点初始化操作,定义了圆点的默认色normalCircleColor,选中色acitiveCircleColor,以及圆点之间的距离circleDivider,

默认圆点的半径circleRadius,选中原点的半径activeCircleRadius,然后根据ViewPager的图片数量进行分装圆点对象集合

然后看onMeasure去测量View的整体大小--不解释了

最后看onDraw就是去绘制圆点,这些方法比较简单


    mPagerIndicator.setActivityCircle(position);这个就是滚动到某一页面进行的逻辑处理

/*** 设置目前活动的小球* 第一部分根据startValue求出其中A,R,G,B中各个色彩的初始值;第二部分根据endValue求出其中A,R,G,B中各个色彩的结束值* ,最后是根据当前动画的百分比进度求出对应的数值*/public void setActivityCircle(int index) {lastCircle = circles.get(activeCircleIndex);lastCircle.color = ColorHelper.evaluate(0.1f, normalCircleColor,acitiveCircleColor);lastCircle.radius = circleRadius;activeCircleIndex = index;currentActivedCircele = circles.get(activeCircleIndex);currentActivedCircele.color = ColorHelper.evaluate(0.1f,acitiveCircleColor, normalCircleColor);currentActivedCircele.radius = activeCircleRadius;invalidate();}

逻辑比较简单,就是判断上一个原点,和目前选中的圆点,然后进行颜色和半径的设置修改,在进行重绘操作

最后看比较复杂的mPagerIndicator.setScrollProgress(position,percent);逻辑处理

public void setScrollProgress(int leftPosition, float percent) {right = circles.get(leftPosition + 1);left = circles.get(leftPosition);// 手指右滑-递减if (lastPercent > percent) {left.radius = circleRadius + (1 - percent)* PhoneUtils.dp2px(getContext(), 2);right.radius = circleRadius + percent* PhoneUtils.dp2px(getContext(), 2);if (left.color == normalCircleColor) {left.color = ColorHelper.evaluate(percent, normalCircleColor,acitiveCircleColor);} else {left.color = ColorHelper.evaluate(percent, acitiveCircleColor,normalCircleColor);}if (right.color == normalCircleColor) {right.color = ColorHelper.evaluate(1 - percent,normalCircleColor, acitiveCircleColor);} else {right.color = ColorHelper.evaluate(1 - percent,acitiveCircleColor, normalCircleColor);}}// 手指左滑-递增if (lastPercent < percent) {left.radius = circleRadius + (1 - percent)* PhoneUtils.dp2px(getContext(), 2);right.radius = circleRadius + percent* PhoneUtils.dp2px(getContext(), 2);if (right.color == normalCircleColor) {right.color = ColorHelper.evaluate(1 - percent,normalCircleColor, acitiveCircleColor);} else {right.color = ColorHelper.evaluate(1 - percent,acitiveCircleColor, normalCircleColor);}if (left.color == normalCircleColor) {left.color = ColorHelper.evaluate(percent, normalCircleColor,acitiveCircleColor);} else {left.color = ColorHelper.evaluate(percent, acitiveCircleColor,normalCircleColor);}}invalidate();lastPercent = percent;}

以上的代码,我感觉还有bug,不过效果基本上出来了,就是判断左右滑动的方向,进行颜色的变化修改


另外还有一下工具类

MeasureUtil

package com.example.pageindicator;  import android.app.Activity;  
import android.util.DisplayMetrics;  /** * 测绘工具�? */  
public final class MeasureUtil {  /** * 获取屏幕尺寸 *  * @param activity *            Activity * @return 屏幕尺寸像素值,下标�?的�?为宽,下标为1的�?为高 */  public static float[] getScreenSize(Activity activity) {  DisplayMetrics metrics = new DisplayMetrics();  activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);  return new float[] { metrics.widthPixels, metrics.heightPixels };  }  
}  


PhoneUtils

package com.example.pageindicator;  import android.content.Context;  public class PhoneUtils {  public static int dp2px(Context context,float dpValue){  float scale = context.getResources().getDisplayMetrics().density;  return (int)(dpValue * scale +0.5f);  }  
}  

ColorHelper

package com.example.pageindicator;import android.animation.ArgbEvaluator;
import android.graphics.Color;public class ColorHelper {private static final String TAG = "ColorHelper";private static ArgbEvaluator colorEvaluator = new ArgbEvaluator();public static Integer evaluate(float fraction,int start,int end ){return (Integer) colorEvaluator.evaluate(fraction, start, end);}}


这篇关于自定义颜色、大小渐变的圆点指示器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

自定义类型:结构体(续)

目录 一. 结构体的内存对齐 1.1 为什么存在内存对齐? 1.2 修改默认对齐数 二. 结构体传参 三. 结构体实现位段 一. 结构体的内存对齐 在前面的文章里我们已经讲过一部分的内存对齐的知识,并举出了两个例子,我们再举出两个例子继续说明: struct S3{double a;int b;char c;};int mian(){printf("%zd\n",s

Spring 源码解读:自定义实现Bean定义的注册与解析

引言 在Spring框架中,Bean的注册与解析是整个依赖注入流程的核心步骤。通过Bean定义,Spring容器知道如何创建、配置和管理每个Bean实例。本篇文章将通过实现一个简化版的Bean定义注册与解析机制,帮助你理解Spring框架背后的设计逻辑。我们还将对比Spring中的BeanDefinition和BeanDefinitionRegistry,以全面掌握Bean注册和解析的核心原理。

Oracle type (自定义类型的使用)

oracle - type   type定义: oracle中自定义数据类型 oracle中有基本的数据类型,如number,varchar2,date,numeric,float....但有时候我们需要特殊的格式, 如将name定义为(firstname,lastname)的形式,我们想把这个作为一个表的一列看待,这时候就要我们自己定义一个数据类型 格式 :create or repla

PDFQFZ高效定制:印章位置、大小随心所欲

前言 在科技编织的快节奏时代,我们不仅追求速度,更追求质量,让每一分努力都转化为生活的甜蜜果实——正是在这样的背景下,一款名为PDFQFZ-PDF的实用软件应运而生,它以其独特的功能和高效的处理能力,在PDF文档处理领域脱颖而出。 它的开发,源自于对现代办公效率提升的迫切需求。在数字化办公日益普及的今天,PDF作为一种跨平台、不易被篡改的文档格式,被广泛应用于合同签署、报告提交、证书打印等各个

HTML5自定义属性对象Dataset

原文转自HTML5自定义属性对象Dataset简介 一、html5 自定义属性介绍 之前翻译的“你必须知道的28个HTML5特征、窍门和技术”一文中对于HTML5中自定义合法属性data-已经做过些介绍,就是在HTML5中我们可以使用data-前缀设置我们需要的自定义属性,来进行一些数据的存放,例如我们要在一个文字按钮上存放相对应的id: <a href="javascript:" d

一步一步将PlantUML类图导出为自定义格式的XMI文件

一步一步将PlantUML类图导出为自定义格式的XMI文件 说明: 首次发表日期:2024-09-08PlantUML官网: https://plantuml.com/zh/PlantUML命令行文档: https://plantuml.com/zh/command-line#6a26f548831e6a8cPlantUML XMI文档: https://plantuml.com/zh/xmi

argodb自定义函数读取hdfs文件的注意点,避免FileSystem已关闭异常

一、问题描述 一位同学反馈,他写的argo存过中调用了一个自定义函数,函数会加载hdfs上的一个文件,但有些节点会报FileSystem closed异常,同时有时任务会成功,有时会失败。 二、问题分析 argodb的计算引擎是基于spark的定制化引擎,对于自定义函数的调用跟hive on spark的是一致的。udf要通过反射生成实例,然后迭代调用evaluate。通过代码分析,udf在

鸿蒙开发中实现自定义弹窗 (CustomDialog)

效果图 #思路 创建带有 @CustomDialog 修饰的组件 ,并且在组件内部定义controller: CustomDialogController 实例化CustomDialogController,加载组件,open()-> 打开对话框 , close() -> 关闭对话框 #定义弹窗 (CustomDialog)是什么? CustomDialog是自定义弹窗,可用于广告、中

mybatis框架基础以及自定义插件开发

文章目录 框架概览框架预览MyBatis框架的核心组件MyBatis框架的工作原理MyBatis框架的配置MyBatis框架的最佳实践 自定义插件开发1. 添加依赖2. 创建插件类3. 配置插件4. 启动类中注册插件5. 测试插件 参考文献 框架概览 MyBatis是一个优秀的持久层框架,它支持自定义SQL、存储过程以及高级映射,为开发者提供了极大的灵活性和便利性。以下是关于M