1、Android TextView文字横向自动滚动(跑马灯)

效果图.png
TextView实现文字滚动需要以下几个要点:
- 1.文字长度长于可显示范围:android:singleLine="true"
- 2.设置可滚到,或显示样式:android:ellipsize="marquee"
- 3.自定义滚动的ScrollingTextView
2、XML布局
<com.kana.crazytv.ui.customer.ScrollingTextView
android:id="@+id/textview"
android:layout_width="@dimen/ui_dp_400"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"
android:layout_marginBottom="@dimen/ui_dp_50"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:text="This is a long text that will be horizontally scrolled This is a long text that will be horizontally scrolled" />
3、ScrollingTextView
package com.kana.crazytv.ui.customer;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
/**
* 自定义文字横向滑动
*/
public class ScrollingTextView extends androidx.appcompat.widget.AppCompatTextView {
public ScrollingTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ScrollingTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ScrollingTextView(Context context) {
super(context);
}
@Override
protected void onFocusChanged(boolean focused, int direction,
Rect previouslyFocusedRect) {
if (focused) {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
}
@Override
public void onWindowFocusChanged(boolean focused) {
if (focused) {
super.onWindowFocusChanged(focused);
}
}
@Override
public boolean isFocused() {
return true;
}
}
网友评论