android TextView 垂直自动滚动字幕实现

openkk 13年前

前段时间,在网上搜到一个帖子,textview 水平自动滚动字幕的实现,今日项目需要垂直滚动字幕。其实现原理和水品一样。都是重写textview的onDraw方法。
实现垂直自动滚动字幕需要2点需要注意
1.需要根据textview的宽度和字体的大小计算滚动字幕有多少行。实现这个功能,需要重新写两个方法:1.onMeasure,2.onDraw.因为需要获取textview的宽度,于是需要在onMeasure方法里面调用如下代码。具体方法如下:

public VerticalScrollTextView extends TextView {      private float step =0f;        private Paint mPaint;      private String text;      private float width;      private List<String> textList = new ArrayList<String>();    //分行保存textview的显示信息。        public VerticalScrollTextView(Context context, AttributeSet attrs) {          super(context, attrs);              }              public VerticalScrollTextView(Context context) {          super(context);              }            @Override      protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {                  super.onMeasure(widthMeasureSpec, heightMeasureSpec);          width = MeasureSpec.getSize(widthMeasureSpec);                   final int widthMode = MeasureSpec.getMode(widthMeasureSpec);            if (widthMode != MeasureSpec.EXACTLY) {                 throw new IllegalStateException("ScrollLayout only canmCurScreen run at EXACTLY mode!");          }                        float length = 0;                    if(text==null|text.length()==0){                  return ;              }                                 //下面的代码是根据宽度和字体大小,来计算textview显示的行数。            textList.clear();                    StringBuilder builder = new StringBuilder();          for(int i=0;i<text.length();i++){              Log.e("textviewscroll",""+i+text.charAt(i));              if(length<width){                  builder.append(text.charAt(i));                  length += mPaint.measureText(text.substring(i, i+1));                  if(i==text.length()-1){                      Log.e("textviewscroll",""+i+text.charAt(i));                      textList.add(builder.toString());                  }              }else{                  textList.add(builder.toString().substring(0,builder.toString().length()-1));              builder.delete(0, builder.length()-1) ;              length= mPaint.measureText(text.substring(i, i+1));              i--;              }                        }      }          //下面代码是利用上面计算的显示行数,将文字画在画布上,实时更新。  &nbsp; &nbsp;&nbsp; @Override      public void onDraw(Canvas canvas) {          for (int i = 0; i < textList.size(); i++) {              canvas.drawText(textList.get(i), 0, this.getHeight()+(i+1)*mPaint.getTextSize()-step, getPaint());          }                        invalidate();              step = step+0.3f;          if (step >= this.getHeight()+textList.size()*mPaint.getTextSize()) {              step = 0;          }              }    }

还有一些扩展功能没有加,比方说滚动的速度设定,滚动多长时间就停止滚动。

转自:http://blog.csdn.net/fengyoujie/article/details/7296941