Android 自定义的颜色滑动转换ViewPager指示器 ColorTransformIndicator

来源:互联网 发布:大数据对日常生活影响 编辑:程序博客网 时间:2024/04/30 15:01

本文参考:http://blog.csdn.net/lmj623565791/article/details/44098729


先来看看效果图

       


一 使用

1 布局 


   添加一个自定义控件

<span style="font-family: Arial, Helvetica, sans-serif;"><?xml version="1.0" encoding="utf-8"?></span>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <com.rios.indicator.indicatior.indicator.Indicator        android:id="@+id/indicator"        android:layout_width="wrap_content"        android:layout_height="wrap_content"         />    <android.support.v4.view.ViewPager        android:id="@+id/viewpager"        android:layout_width="match_parent"        android:layout_height="match_parent" >    </android.support.v4.view.ViewPager></LinearLayout>

添加一个背景用的shape.xml

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">    <corners android:radius="5dp"/><solid android:color="#5000"/></shape>


2 代码调用

mIndicator = (Indicator) findViewById(R.id.indicator);ViewPager = (ViewPager) findViewById(R.id.viewpager);


private String[] mTitles = {"同城", "笑话", "图片","天气","电影","音乐","机票","彩票","游戏","小说","股票","理财","新闻","军事","社会","娱乐"};private void setIndicator() {//移动方块背景颜色更改 shape_indicator.xmlmIndicator.setViewPager(mViewPager);mIndicator.setTitleString(mTitles);//mTitles的大小要和mViewPager的大小一致//mIndicator.setColorTextBack(Color.BLACK);//设置字体背景颜色//mIndicator.setColorTextCurrent(0xFFF0FFFF);//设置字体选择时的颜色//mIndicator.setBackgroundColor(0xFFFF6A6A);//设置背景颜色//mIndicator.setTitleTextSize(20);//设置字体大小mIndicator.setParams();//使以上参数生效mIndicator.setOnClickItemListener(new Indicator.OnClickItemListener() {@Overridepublic void OnItemClick(View childView, int position) {Toast.makeText(IndicatorActivity.this,"你点击的是:"+position+"  "+((TextView)childView).getText().toString(),Toast.LENGTH_SHORT).show();}});mViewPager.setOnPageChangeListener(new OnPageChangeListener() {@Overridepublic void onPageSelected(int position) {}@Overridepublic void onPageScrolled(int position, float positionOffset,   int positionOffsetPixels) {//--------------设置颜色切换位置mIndicator.setPosition(position, positionOffset);}@Overridepublic void onPageScrollStateChanged(int state) {}});}


很简单吧


二 原理

 字体颜色转换原理是绘了二次字体 ,第一次全绘,第二次绘需要的范围,那绘范围怎么绘呢,其实有个方法能实现 就是 

canvas.clipRect  只能在矩形区域里绘制

mPaint.setColor(mColorTextBack);
//第一次全绘canvas.drawText(mAttrText, 0, mHeight, mPaint);mPaint.setColor(mColorTextCurrent);
//限制范围canvas.clipRect(mRect);
//第二次绘canvas.drawText(mAttrText, 0, mHeight, mPaint);
三 源码下载
https://github.com/rios168/ColorTransformIndicator
如果好用 记得点击 star 支持

0 0
原创粉丝点击