前言
這段時間有點小偷懶_,好久沒有更新文章了口猜,想想都有點罪惡感ヽ(●-`Д′-)ノ。為了彌補(bǔ)我的罪惡感恨狈,我準(zhǔn)備給自己的博客新加一個系列————好用的開源項目(PS:名字有點low,大家多多包含)糙臼, 這個系列將為大家?guī)?GitHub 上面一些好用庐镐、有趣開源項目的使用,及個人的一點小見解(我會盡量月月更的变逃。焚鹊。。)韧献。讓我們一起學(xué)習(xí)吧末患!一起進(jìn)步吧!
本博客同步發(fā)布于XueLong的博客
作為本系列的第一個開源項目锤窑,今天的主角是————RevealTextView
項目地址: https://github.com/ANPez/RevealTextView
簡介
A TextView subclass to show a reveal effect
文字淡入效果的TextView璧针。
運行環(huán)境:Android 4.0+, API 14+
使用方式:
Gradle依賴:
dependencies {
compile 'com.antonionicolaspina:revealtextview:2.0'
}
布局文件中:
<com.antonionicolaspina.revealtextview.RevealTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:rtv_duration="2000"
android:text="Hello Reveal Text!"/>
效果圖
實現(xiàn)思路
自定義TextView,利用多線程控制動畫的時間渊啰,主要是借助SpannableStringBuilder
來實現(xiàn)文字的閃爍效果的探橱。
首先在初始化時,調(diào)用開始動畫的操作
protected void init(TypedArray attrs) {
try {
animationDuration = attrs.getInteger(R.styleable.RevealTextView_rtv_duration, animationDuration);
text = attrs.getString(R.styleable.RevealTextView_android_text);
} finally {
attrs.recycle();
}
setAnimatedText(text);
}
在設(shè)置動畫字體的方法中绘证,生成接下來要使用的透明度的隨機(jī)值隧膏、設(shè)置文字顯示、以及重放動畫效果嚷那。
public void setAnimatedText(String text) {
if (TextUtils.isEmpty(text)) {
return;
}
this.text = text;
alphas = new double[text.length()];
for (int i = 0; i < text.length(); i++) {
alphas[i] = Math.random() - 1.0f;
}
setText(text);
replayAnimation();
}
接下來就是在run方法中啟動動畫胞枕。
@Override
public void run() {
final int color = getCurrentTextColor();
red = Color.red(color);
green = Color.green(color);
blue = Color.blue(color);
ValueAnimator animator = ValueAnimator.ofFloat(0f, 2f);
animator.setDuration(animationDuration);
animator.setInterpolator(new LinearInterpolator());
animator.addUpdateListener(this);
if (isLoop) {
animator.setRepeatMode(ValueAnimator.REVERSE);
animator.setRepeatCount(ValueAnimator.INFINITE);
}
animator.start();
}
最后就是關(guān)于動畫的更新。
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
final float value = (float) valueAnimator.getAnimatedValue();
SpannableStringBuilder builder = new SpannableStringBuilder(text);
for(int i=0; i<text.length(); i++) {
builder.setSpan(new ForegroundColorSpan(Color.argb(clamp(value + alphas[i]), red, green, blue)), i, i+1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
setText(builder);
}
寫在最后
講解可能不是很清楚魏宽,還存在著諸多漏洞腐泻,請多包涵。
如果你在參考過程中遇到問題队询,可以在我的聯(lián)系方式中給我提問派桩。
后面會繼續(xù)介紹,Android的相關(guān)知識蚌斩,歡迎繼續(xù)關(guān)注我博客的更新铆惑。
參考資源
轉(zhuǎn)載請注明:XueLong的博客 ? 好用的開源項目--RevealTextView