標籤:android textview span 監聽 跑馬燈
TextView都有跑馬燈的效果,如果說讓你去監聽跑馬燈效果的執行,我覺得這個需求有點二了,但是也要實現。思路:1.自訂View 繼承TextView 這種方法過於麻煩,只是監聽一個跑馬燈而已。2.自訂SPan。簡單好用,擴充TextView的功能。
關鍵代碼如下:
@Override public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) { canvas.save(); canvas.drawText( text.toString(), x - startX, y, paint); canvas.restore(); int measureText = (int) paint.measureText(text, 0, text.length()); if (valueAnimator == null ) { initAnimator(measureText - mView.getWidth()); } } private int startX = 0 ; private final static int DEFULT_DURATION = 2000 ; private int duration = DEFULT_DURATION ; @Override public int getSize(Paint paint, CharSequence text, int start, int end, FontMetricsInt fm) { return 40; } private void initAnimator(int width ){ valueAnimator = ValueAnimator.ofInt(0, width , 0 ); valueAnimator.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { startX = (Integer) animation.getAnimatedValue() ; mView.invalidate(); } }); valueAnimator.setInterpolator(new LinearInterpolator()); valueAnimator.setDuration(duration); valueAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationRepeat(Animator animation) { if (mEasySpanListener != null ) { mEasySpanListener.over(); } } }); valueAnimator.setRepeatCount(Integer.MAX_VALUE); valueAnimator.start(); }
Span本身就是對TextView的一個功能增強。使用: String text = "這個是用來測試的,TextView的跑馬燈效果,想要監聽他的跑完的事件用的。" ; SpannableString spannableString = new SpannableString(text); EasySpan easySpan =new EasySpan(MainActivity.this,test); easySpan.setDuration(10000); easySpan.setEasySpanListener(new EasySpanListener() { @Override public void over() { Log.i("Test", "over") ; } }); spannableString.setSpan(easySpan, 0, text.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); test.setText(spannableString);
很簡單的小功能,大家就看代碼吧。 源碼: https://github.com/flyme2012/EasyListenerSpan
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
Android自訂之TextView跑馬燈的監聽