TextView自帶的走馬燈效果在失去焦點的情況下會無效,公司正好需要一個這樣的效果,即使失去焦點走馬燈效果依然存在,那麼該怎麼做呢?網上亂七八糟的代碼一大堆,寫的那麼復雜,所以我就寫了一個簡單的例子,下面直接上代碼了。
1.自定義TextView:
- package com.zhf.TextAutoMoveDemo;
-
- import Android.content.Context;
- import android.graphics.Canvas;
- import android.graphics.Color;
- import android.util.AttributeSet;
- import android.widget.TextView;
-
- /**
- * 自定義TextView,TextView自帶了該功能,但功能有限,最重要的是TextView失去焦點的情況下走馬燈效果會暫停!
- *
- * @author administrator
- *
- */
- public class MyTextView extends TextView implements Runnable {
- private Text text;
-
- public MyTextView(Context context, AttributeSet attrs) {
- super(context, attrs);
- text = new Text(
- "走馬燈效果演示...",
- 0, 20, 5);
- }
-
- public void startMove() {
- Thread thread = new Thread(this);
- thread.start();
- }
-
- @Override
- public void run() {
- try {
- while (true) {
- // 1.刷新
- postInvalidate();
- // 2.睡眠
- Thread.sleep(200L);
- // 3.移動
- text.move();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Override
- protected void onDraw(Canvas canvas) {
- // 背景色
- canvas.drawColor(Color.WHITE);
- // 繪制文字
- text.draw(canvas);
- }
-
- }
2.實體類Text
- package com.zhf.TextAutoMoveDemo;
-
- import android.graphics.Canvas;
- import android.graphics.Color;
- import android.graphics.Paint;
-
- public class Text {
- private Paint paint;
- private String content;//文字內容
- private float x;//x坐標
- private float y;//y坐標
- private float stepX;//移動步長
- private float contentWidth;//文字寬度
- public Text(String content, float x, float y, float stepX) {
- this.content = content;
- this.x = x;
- this.y = y;
- this.stepX = stepX;
- //畫筆參數設置
- paint = new Paint();
- paint.setColor(Color.RED);
- paint.setTextSize(20f);
- this.contentWidth = paint.measureText(content);
- }
-
- public void move() {
- x -= stepX;
- if (x < -contentWidth)//移出屏幕後,從右側進入
- x = 320;//屏幕寬度,真實情況下應該動態獲取,不能寫死
- }
-
- public void draw(Canvas canvas) {
- canvas.drawText(content, x, y, paint);
- }
- }