本文主要是介绍自定义的跑马灯控件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
随时随地技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)
原文转自:农民伯伯:【Android】不依赖焦点和选中的TextView跑马灯【2】 - 农民伯伯 - 博客园
package com.home.view;import com.home.util.DataUtil;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.TextView;/*** 自定义的跑马灯控件* * @author fengjian* */
public class MarqueeView extends TextView {/** 是否停止滚动 */private boolean mStop;private String mText;private float mCoordinateX;private float mTextWidth;public MarqueeView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);}public MarqueeView(Context context, AttributeSet attrs) {super(context, attrs);}public MarqueeView(Context context) {super(context);}/*** 设置文本并启动跑马灯效果* * @param text* 文本内容*/public void setText(String text) {this.mText = text;mTextWidth = getPaint().measureText(mText);if (mHandler.hasMessages(0))mHandler.removeMessages(0);mHandler.sendEmptyMessageDelayed(0, 2000);}/*** 停止跑马灯效果*/public void stop() {mStop = true;}@Overrideprotected void onAttachedToWindow() {mStop = false;if (!DataUtil.isEmpty(mText))mHandler.sendEmptyMessageDelayed(0, 2000);super.onAttachedToWindow();}@Overrideprotected void onDetachedFromWindow() {mStop = true;if (mHandler.hasMessages(0))mHandler.removeMessages(0);super.onDetachedFromWindow();}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);if (!DataUtil.isEmpty(mText))canvas.drawText(mText, mCoordinateX, 15, getPaint());}@SuppressLint("HandlerLeak")private Handler mHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case 0:if (Math.abs(mCoordinateX) > (mTextWidth + 100)) {mCoordinateX = 0;invalidate();if (!mStop) {sendEmptyMessageDelayed(0, 2000);}} else {mCoordinateX -= 1;invalidate();if (!mStop) {sendEmptyMessageDelayed(0, 30);}}break;}super.handleMessage(msg);}};}
这篇关于自定义的跑马灯控件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!