我的github

Android自定义之TextView跑马灯的监听

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/blob/master/src/com/example/easylistenerspan/MainActivity.java>
 
 

很简单的小功能,大家就看代码吧。
 
源码下载地址:   https://github.com/flyme2012/EasyListenerSpan   
 





posted @ 2015-07-09 20:55  陌上尖  阅读(1334)  评论(0编辑  收藏  举报