我正在尝试实现一个会自动滚动的单行文本视图。但不幸的是,我无法让它发挥作用。 AutoScrollTextView 在 LinearLayout 中声明(宽度和高度 = fill_parent)。该类基本上使用一个处理程序,该处理程序调用自身以滚动给定数量。我已经简化了代码,只显示一个应该每秒滚动 5 个像素的文本视图。
日志输出正确,getScrollX() 方法返回相应的scrollX 位置。
如果我不调用 requestLayout()
,则不会绘制任何内容。 invalidate()
没有效果。
有人会有线索吗?
public class AutoScrollTextView extends TextView {
public AutoScrollTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setSingleLine();
setEllipsize(null);
setText("Single-line text view that scrolls automatically if the text is too long to fit in the widget");
}
// begin to scroll the text from the original position
public void startScrolling() {
scrollHandler.sendEmptyMessage(0);
}
private Handler scrollHandler = new Handler() {
private static final int REFRESH_INTERVAL = 1000;
public void handleMessage(Message msg) {
scrollBy(5, 0);
requestLayout();
Log.debug("Scrolled to " + getScrollX() + " px");
sendEmptyMessageDelayed(0, REFRESH_INTERVAL);
}
};
}
原文由 Vincent Mimoun-Prat 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果您不需要子类
TextView
,您可以在布局文件中尝试:此外,在您的代码中使用以下内容:
[根据评论编辑答案]