Preface
I wrote a textView marquee * before. Later, I found new problems in the actual project, such as the problem of not being able to run automatically and the text is intercepted if it exceeds the display area. Today I changed my thinking to implement it, which is simpler and more useful.
text
Code implementation:
public class MarqueeTextView extends TextView { /** Whether to stop scrolling */ 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) { = text; mTextWidth = getPaint().measureText(mText); if ((0)) (0); (0, 2000); } @Override protected void onAttachedToWindow() { mStopMarquee = false; if (!(mText)) (0, 2000); (); } @Override protected void onDetachedFromWindow() { mStopMarquee = true; if ((0)) (0); (); } @Override protected void onDraw(Canvas canvas) { (canvas); if (!(mText)) (mText, mCoordinateX, 15, getPaint()); } private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch () { case 0: if ((mCoordinateX) > (mTextWidth + 100)) { mCoordinateX = 0; invalidate(); if (!mStopMarquee) { sendEmptyMessageDelayed(0, 2000); } } else { mCoordinateX -= 1; invalidate(); if (!mStopMarquee) { sendEmptyMessageDelayed(0, 30); } } break; } (msg); } }; }
Code description:
1. 2000 means delaying 2 seconds to start the marquee effect
2. mTextWidth + 100 means running out of the screen for 100 pixels and then starting to run again
3. Move 1 pixel every 30 milliseconds
4. The principle is very simple, which is to brush regularly. The usage is very simple. Just setText directly. It is the same as using the system, but you cannot run directly by setting the value of xml. This can be modified by yourself.
5. Pay attention to determining whether text is empty when onDraw, just replace it with your own judgment method.
The above is the example code for Android implementation of marquee *s. Friends who need it can refer to it.