Android TextView失去焦点后仍然实现文字滚动效果

Bertha 。 2022-11-09 11:21 407阅读 0赞

一、前言

有些时候TextView显示的长度不够需要实现滚动效果,有时候layout布局文件设置了一些属性后,能够实现滚动效果。但是TextView一旦失去焦点,滚动效果就停止了。

二、思路

重写TextView内部的方法,当失去焦点时仍然使其滚动。

三、参考代码

1. Java代码实现

  1. package com.example.getsystempropclient;
  2. import android.annotation.SuppressLint;
  3. import android.content.Context;
  4. import android.graphics.Rect;
  5. import android.util.AttributeSet;
  6. import android.widget.TextView;
  7. @SuppressLint("AppCompatCustomView")
  8. public class ScrollTestView extends TextView {
  9. public ScrollTestView(Context context) {
  10. super(context);
  11. }
  12. public ScrollTestView(Context context, AttributeSet attrs, int defStyle) {
  13. super(context, attrs, defStyle);
  14. }
  15. public ScrollTestView(Context context, AttributeSet attrs) {
  16. super(context, attrs);
  17. }
  18. @Override
  19. public boolean isFocused() {
  20. return true;
  21. }
  22. @Override
  23. protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
  24. if (focused) { // 修改的地方
  25. super.onFocusChanged(focused, direction, previouslyFocusedRect);
  26. }
  27. }
  28. @Override
  29. public void onWindowFocusChanged(boolean hasWindowFocus) {
  30. if (hasWindowFocus) { // 修改的地方
  31. super.onWindowFocusChanged(hasWindowFocus);
  32. }
  33. }
  34. }

2. xml布局文件

  1. <com.example.getsystempropclient.ScrollTestView android:id="@+id/tv_compile_time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:focusableInTouchMode="true" android:singleLine="true" android:focusable="true" android:ellipsize="marquee" android:marqueeRepeatLimit="marquee_forever" />

一点说明:
根据自实际需求,xml文件中添加android:focusableInTouchMode、android:singleLine、android:focusable、android:ellipsize、android:marqueeRepeatLimit几个属性。

发表评论

表情:
评论列表 (有 0 条评论,407人围观)

还没有评论,来说两句吧...

相关阅读