/**
* 当触摸该控件是会滚动
*/
public class ZDYMarqueeText extends TextView {
private int speed = 3;// 默认移动的速度
private int time = 50;// 每个50毫秒
private boolean isStop;// 是否停止滚动
private String mText;// 文本内容
private int mTextWidth;// 文本的宽度
private int mCurrentScrollX;// X轴坐标
public ZDYMarqueeText(Context context) {
super(context);
}
public ZDYMarqueeText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ZDYMarqueeText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == 0x11) {
mCurrentScrollX += speed;// 计算x轴滑动的距离
if (mCurrentScrollX > mTextWidth) {
scrollTo(0, 0);// 若距离大于文本宽度,则重新计算
mCurrentScrollX = 0;
} else {
scrollTo(mCurrentScrollX, 0);// 滚动到指定的位置
}
}
}
};
/**
* 启动滚动效果,并执行一些初始化操作
*/
public void start() {
mText = getText().toString();// 获取滚动文本内容
mTextWidth = (int) getPaint().measureText(mText);// 计算文本的宽度
mCurrentScrollX = 0;// X轴坐标默认为0
startThread();
}
public void startThread() {
isStop = false;
new Thread() {
public void run() {
if (!isStop) {
try {
mHandler.sendEmptyMessage(0x11);
Thread.sleep(time);
} catch (Exception e) {
e.printStackTrace();
}
}
};
}.start();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_SCROLL://按下、拖动、滑动
pause();
break;
default:
gonOn();
break;
}
return true;//点击才能动
}
//滚动
private void gonOn() {
startThread();
}
//暂停
private void pause() {
isStop=true;
}
}
//在主窗体中调用
public class ZDYMarqueeActivity extends Activity {
private ZDYMarqueeText textview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zdy_marquee);
textview=(ZDYMarqueeText) this.findViewById (R.id.zdy_marquee);
textview.start();//启动滚动效果
}
}
//编辑XML布局文件(主要代码)