Android TextView失去焦点后仍然实现文字滚动效果
一、前言
有些时候TextView
显示的长度不够需要实现滚动效果,有时候layout
布局文件设置了一些属性后,能够实现滚动效果。但是TextView
一旦失去焦点,滚动效果就停止了。
二、思路
重写TextView
内部的方法,当失去焦点时仍然使其滚动。
三、参考代码
1. Java代码实现
package com.example.getsystempropclient;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.TextView;
@SuppressLint("AppCompatCustomView")
public class ScrollTestView extends TextView {
public ScrollTestView(Context context) {
super(context);
}
public ScrollTestView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ScrollTestView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean isFocused() {
return true;
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if (focused) { // 修改的地方
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
if (hasWindowFocus) { // 修改的地方
super.onWindowFocusChanged(hasWindowFocus);
}
}
}
2. xml布局文件
<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
几个属性。
还没有评论,来说两句吧...