public static enum TruncateAt {
END,
MARQUEE,
MIDDLE,
START;
private TruncateAt() {
}
MARQUEE,即跑马灯效果
frameworks/base/./core/java/android/widget/TextView.java
/**
* Causes words in the text that are longer than the view is wide
* to be ellipsized instead of broken in the middle. You may also
* want to {@link #setSingleLine} or {@link #setHorizontallyScrolling}
* to constrain the text to a single line. Use <code>null</code>
* to turn off ellipsizing.
*
* If {@link #setMaxLines} has been used to set two or more lines,
* only {@link android.text.TextUtils.TruncateAt#END} and
* {@link android.text.TextUtils.TruncateAt#MARQUEE} are supported
* (other ellipsizing types will not do anything).
*
* @attr ref android.R.styleable#TextView_ellipsize
*/
public void setEllipsize(TextUtils.TruncateAt where) {
// TruncateAt is an enum. != comparison is ok between these singleton objects.
if (mEllipsize != where) {
mEllipsize = where;
if (mLayout != null) {
nullLayouts();
requestLayout();
invalidate();
}
}
}
/**
* Sets how many times to repeat the marquee animation. Only applied if the
* TextView has marquee enabled. Set to -1 to repeat indefinitely.
*
* @see #getMarqueeRepeatLimit()
*
* @attr ref android.R.styleable#TextView_marqueeRepeatLimit
*/
public void setMarqueeRepeatLimit(int marqueeLimit) {
mMarqueeRepeatLimit = marqueeLimit;
}
private boolean canMarquee() {
int width = (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight());
return width > 0 && (mLayout.getLineWidth(0) > width ||
(mMarqueeFadeMode != MARQUEE_FADE_NORMAL && mSavedMarqueeModeLayout != null &&
mSavedMarqueeModeLayout.getLineWidth(0) > width));
}
private void startMarquee() {
// Do not ellipsize EditText
if (getKeyListener() != null) return;
if (compressText(getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight())) {
return;
}
//执行startMarquee()下面的代码需要2个条件
//isFoused()或isSelected()为true
//lineCount为1
if ((mMarquee == null || mMarquee.isStopped()) && (isFocused() || isSelected()) &&
getLineCount() == 1 && canMarquee()) {
if (mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) {
mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_FADE;
final Layout tmp = mLayout;
mLayout = mSavedMarqueeModeLayout;
mSavedMarqueeModeLayout = tmp;
setHorizontalFadingEdgeEnabled(true);
requestLayout();
invalidate();
}
if (mMarquee == null) mMarquee = new Marquee(this);
mMarquee.start(mMarqueeRepeatLimit);
}
}
因此,对于Android源生的TextView,想要有跑马灯效果,有三个必要条件:
1. android:singleLine=”true”
2. android:focusable=”true”
android:focusableInTouchMode=”true”
3. android:ellipsize=”marquee”
4. android:width为固定值,如50dp。
以上属性都通过xml或者java代码设置成功,在TextView获得焦点,并且文本长度超过该width值时显示跑马灯效果。
android:marqueeRepeatLimit=”marquee_forever”表示永远执行跑马灯效果。
对应java代码为setMarqueeRepeatLimit(-1);
不设置的话,默认执行三次。