android跑马灯控件
基于TextView的Android跑马灯控件
网上很多的跑马灯有的是控制滚轴实现拖动,有的是配置textview的属性,但是在控件没有获得焦点或选中的的状态下不能很好的运行。
本控件通过重写textview,自动计算字体大小以及绘制的坐标,使用cavans渲染。可以在没有获得焦点、页面上有多个需要跑马灯的场合应用。
package com.example.test;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.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;
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);
Paint paint = getPaint();
int viewHeight = getHeight();
FontMetrics fm = paint.getFontMetrics();
float textCenterVerticalBaselineY = viewHeight / 2 - fm.descent
+ (fm.descent - fm.ascent) / 2;
canvas.drawText(mText, mCoordinateX, textCenterVerticalBaselineY,
getPaint());
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasWindowFocus);
mCoordinateX = getWidth();
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
if (mCoordinateX < 0
&& Math.abs(mCoordinateX) > (mTextWidth + 100)) {
mCoordinateX = getWidth();
;
invalidate();
if (!mStopMarquee) {
sendEmptyMessageDelayed(0, 2000);
}
} else {
mCoordinateX -= 1;
invalidate();
if (!mStopMarquee) {
sendEmptyMessageDelayed(0, 90);
}
}
break;
}
super.handleMessage(msg);
}
};
}
在xml文件引用即可,跟使用普通的textview一样:
<com.example.simple.MarqueeTextView
android:id="@+id/test"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#339320"
android:singleLine="true"
android:textColor="#000000"
android:textSize="35sp" >
</com.example.simple.MarqueeTextView >
本文转自网络,此控件未经本人验证。珍爱生命,紧作参考

浙公网安备 33010602011771号