TextView跑马灯效果
当TextView
内容过多时默认会采用截取的方式以...
来截取。如何能够实现内容过多时的跑马灯效果。
TextView跑马灯效果实现方式一:
改造TextView,自定义View继承的TextView
自定义视图步骤:
- 自定义一个类继承
TextView
,重写它的isFocused()
方法 - 在布局的文件中使用自定义的
TextView
示例代码:
- 继承TextView
//继承TextView并且实现抽象方法
public class FocusedTextView extends TextView {
public FocusedTextView(Context context, AttributeSet attrs, int defStyle){
super(context, attrs, defStyle);
}
public FocusedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FocusedTextView(Context context) {
super(context);
}
//重写isFocused方法,让其一直返回true
public boolean isFocused() {
return true;
}
}
- 在清单文件中使用该类
<com.charon.test.ui.FocusedTextView //注意这里要使用包名.类名
android:ellipsize="marquee"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:text="我们已经收到了来自各位的反馈,麦克雷确实太强了,但是我们并不打算削弱他,因为我们也害怕被他六连”——暴雪" />
TextView跑马灯效果实现方式二:
原生Android的属性,直接申明TextView属性
TextView实现跑马灯的效果,不用自定义View
<TextView
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"
android:text="没有什么是闪光弹+六连无法解决的,如果有,就翻滚再来一次六连。——麦克雷 麦克雷六连的速度太快了,比我的闪现速度还快!——猎空" />
TextView跑马灯效果实现方式三:
利用HorizontalScrollView控件的特性,里面加个TextView,通过定时器让HorizontalScrollView循环滑动,达到跑马灯效果。
public class HorizontalScorllTextView extends HorizontalScrollView implements Runnable{
int currentScrollX = 0;// 当前滚动的位置
TextView tv;
public HorizontalScorllTextView(Context context) {
super(context);
initView(context);
}
public HorizontalScorllTextView(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
public HorizontalScorllTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView(context);
}
void initView(Context context){
View v = LayoutInflater.from(context).inflate(R.layout.scroll_layout, null);
tv = (TextView)v.findViewById(R.id.tv_video_name);
this.addView(v);
}
public void setText(String text){
tv.setText(text);
startScroll();
}
private void startScroll(){
this.removeCallbacks(this);
post(this);
}
@Override
public void run() {
// TODO Auto-generated method stub
currentScrollX ++;// 滚动速度
scrollTo(currentScrollX, 0);
if (currentScrollX >= tv.getWidth()) {
scrollTo(0, 0);
currentScrollX = 0;
}
postDelayed(this, 50);
}
}
- 邮箱 :yjciscrgo@gmail.com