Android 實現不依賴焦點和選中的TextView跑馬燈_Android

來源:互聯網
上載者:User

前言

 之前有寫一篇TextView跑馬燈的效果,後來實際項目中有發現新的問題,比如還是無法自動跑,文本超過了顯示地區就截取的問題,今天換了一種思路來實現,更簡單更好用。

本文

        代碼實現:

public class MarqueeTextView extends TextView {  /** 是否停止滾動 */  private boolean mStopMarquee;  private String mText;  private float mCoordinateX;  private float mTextWidth;  public MarqueeTextView(Context context, AttributeSet attrs) {    super(context, attrs);  }  public void setText(String text) {    this.mText = text;    mTextWidth = getPaint().measureText(mText);    if (mHandler.hasMessages(0))      mHandler.removeMessages(0);    mHandler.sendEmptyMessageDelayed(0, 2000);  }  @Override  protected void onAttachedToWindow() {    mStopMarquee = false;    if (!StringUtils.isEmpty(mText))      mHandler.sendEmptyMessageDelayed(0, 2000);    super.onAttachedToWindow();  }  @Override  protected void onDetachedFromWindow() {    mStopMarquee = true;    if (mHandler.hasMessages(0))      mHandler.removeMessages(0);    super.onDetachedFromWindow();  }  @Override  protected void onDraw(Canvas canvas) {    super.onDraw(canvas);    if (!StringUtils.isEmpty(mText))      canvas.drawText(mText, mCoordinateX, 15, getPaint());  }  private Handler mHandler = new Handler() {    @Override    public void handleMessage(Message msg) {      switch (msg.what) {      case 0:        if (Math.abs(mCoordinateX) > (mTextWidth + 100)) {          mCoordinateX = 0;          invalidate();          if (!mStopMarquee) {            sendEmptyMessageDelayed(0, 2000);          }        } else {          mCoordinateX -= 1;          invalidate();          if (!mStopMarquee) {            sendEmptyMessageDelayed(0, 30);          }        }        break;      }      super.handleMessage(msg);    }  };}

代碼說明:

  1、2000表示延遲2秒開始跑馬燈效果

  2、mTextWidth + 100 表示跑出螢幕100像素再重新開始跑

  3、每30毫秒移動1像素

  4、原理很簡單,就是定時刷,用法很簡單,直接setText就行,和用系統的一樣,但是不能通過設定xml的值來直接跑,這個可以自己修改。

  5、注意onDraw時判定一下text是否為空白,這裡StringUtils.isEmpty替換成自己的判定方法即可。

以上就是Android 實現跑馬燈的執行個體代碼,有需要的朋友可以參考下。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.