需求:有个文字显示,超出显示范围的跑马灯展示,且有个阴影展示。
问题;这个功能比较寻常,但是TextView跑马灯效果是在有焦点的情况下才会跑,做的界面中有个recyclerview会一直占用焦点,需要重写TextView,一直在获取焦点状态。
实现:
1、xml代码:
<com.example.MarqueeTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true" />
2、自定义TextView一直在获取焦点状态:
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
@SuppressLint("AppCompatCustomView")
public class MarqueeTextView extends TextView {
public MarqueeTextView(Context context) {
super(context);
}
public MarqueeTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MarqueeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean isFocused() {
return true;
}
}
3、加阴影效果:
<com.example.MarqueeTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:marqueeRepeatLimit="marquee_forever"
android:shadowColor="#ff000000"
android:shadowDx="0"
android:shadowDy="0"
android:singleLine="true" />
android:shadowColor:阴影的颜色
android:shadowDx:水平方向向右的偏移量
android:shadowDy:垂直方向向下的偏移量
android:shadowRadius:是阴影的的半径,越大越模糊
4、TextView其他问题总结:
(1)文字出现没有到边界就折行的问题,可以在TextView中加入下面的属性:
android:breakStrategy="simple"
(2)设置文字居中,属性android:gravity=“center”,设置以后文字显示偏下,可以修改为:
android:gravity="center_horizontal"
只设置横向居中就行,纵向的是默认的。
参考链接:
Android TextView高级用法
Android TextView跑马灯设置 的 两种方法
Android TextView加上阴影效果