歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android之重寫TextView實現走馬燈效果

Android之重寫TextView實現走馬燈效果

日期:2017/3/1 10:41:48   编辑:Linux編程

TextView自帶的走馬燈效果在失去焦點的情況下會無效,公司正好需要一個這樣的效果,即使失去焦點走馬燈效果依然存在,那麼該怎麼做呢?網上亂七八糟的代碼一大堆,寫的那麼復雜,所以我就寫了一個簡單的例子,下面直接上代碼了。

1.自定義TextView:

  1. package com.zhf.TextAutoMoveDemo;
  2. import Android.content.Context;
  3. import android.graphics.Canvas;
  4. import android.graphics.Color;
  5. import android.util.AttributeSet;
  6. import android.widget.TextView;
  7. /**
  8. * 自定義TextView,TextView自帶了該功能,但功能有限,最重要的是TextView失去焦點的情況下走馬燈效果會暫停!
  9. *
  10. * @author administrator
  11. *
  12. */
  13. public class MyTextView extends TextView implements Runnable {
  14. private Text text;
  15. public MyTextView(Context context, AttributeSet attrs) {
  16. super(context, attrs);
  17. text = new Text(
  18. "走馬燈效果演示...",
  19. 0, 20, 5);
  20. }
  21. public void startMove() {
  22. Thread thread = new Thread(this);
  23. thread.start();
  24. }
  25. @Override
  26. public void run() {
  27. try {
  28. while (true) {
  29. // 1.刷新
  30. postInvalidate();
  31. // 2.睡眠
  32. Thread.sleep(200L);
  33. // 3.移動
  34. text.move();
  35. }
  36. } catch (Exception e) {
  37. e.printStackTrace();
  38. }
  39. }
  40. @Override
  41. protected void onDraw(Canvas canvas) {
  42. // 背景色
  43. canvas.drawColor(Color.WHITE);
  44. // 繪制文字
  45. text.draw(canvas);
  46. }
  47. }

2.實體類Text

  1. package com.zhf.TextAutoMoveDemo;
  2. import android.graphics.Canvas;
  3. import android.graphics.Color;
  4. import android.graphics.Paint;
  5. public class Text {
  6. private Paint paint;
  7. private String content;//文字內容
  8. private float x;//x坐標
  9. private float y;//y坐標
  10. private float stepX;//移動步長
  11. private float contentWidth;//文字寬度
  12. public Text(String content, float x, float y, float stepX) {
  13. this.content = content;
  14. this.x = x;
  15. this.y = y;
  16. this.stepX = stepX;
  17. //畫筆參數設置
  18. paint = new Paint();
  19. paint.setColor(Color.RED);
  20. paint.setTextSize(20f);
  21. this.contentWidth = paint.measureText(content);
  22. }
  23. public void move() {
  24. x -= stepX;
  25. if (x < -contentWidth)//移出屏幕後,從右側進入
  26. x = 320;//屏幕寬度,真實情況下應該動態獲取,不能寫死
  27. }
  28. public void draw(Canvas canvas) {
  29. canvas.drawText(content, x, y, paint);
  30. }
  31. }

Copyright © Linux教程網 All Rights Reserved