这是我参与8月更文挑战的第1天,活动详情查看:8月更文挑战
前言
MarqueeText
的实现方式有很多种,最简单的实现就是TextView
的ellipsize 属性设置为true
android:ellipsize="marquee"
但是这种方式下,在 其不聚焦时候显然不会滚动。
方式1
为了简单起见,我只想在网上搜索一个最简单的能实现在不聚焦情况下能滚动的TextView。 在搜过过程也发现了其他比较好的 MarqueeView,在此附上链接。
- MarqueeView
- MarqueeViewLibrary
但是引入依赖库,这并不是我想要的,我喜欢更简洁的方式。
通过搜索,发现了如下方法。继承
AppCompatTextView
,将 其isFocused
重写,如此TextView
将认为自己已获取焦点,保持滚动。
public class MarqueeText extends AppCompatTextView {
public MarqueeText(@NonNull Context context) {
super(context);
}
public MarqueeText(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public MarqueeText(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean isFocused() {
return true;
}
}
当然配置不要忘了设置 滚动属性
<MarqueeText
...
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"
android:ellipsize="marquee"
/>
但是以上方式,却给我带来了一个巨大的问题。因为 该 MarqueeText
是作为RecyclerView
的一个item
,而 RecyclerView
是用于显示搜索结果的,当搜索关键字变更,RecyclerView
的Adapter
数据将更新,数据更新,将会刷新MarqueeText
,而MarqueeText
的 isFoucesed
始终返回true,其将会抢占了 SearchView
中EditText
的焦点,因此搜索结果更新后,输入法就会立刻隐藏,且再次点击也无法弹出。
这个问题大概花了1天的时间才发现原因,如此一来,方式一 自然是不可用的了。
方式二
方式一已经弃用了,但是Marquee效果还是必须得实现啊,只好自己去看TextView的源码,然后发现还有一种更简单的方式,去实现该效果。
只要在代码中,对 TextView
调用setSelect(true)
即可实现滚动效果。
TextView tv = findByViewId(R.id.tv_marquee);
tv.setSelect(true);
当然,xml配置还是要设置 marquee
值的
<TextView
...
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"
android:ellipsize="marquee"
/>
总结
RecyclerView 与EditText 同时出现时,千万要注意 RecyclerView中的item是否有抢占焦点。