您的位置:首页 > 其它

TextView实现跑马灯

2015-11-09 09:36 106 查看
好像几天都没来写博客了,停止了学习,一下子堕落了,不管学的什么小知识点,都应该记录下来,写代码,做案例。现在来用TextView实现跑马灯。
有时候一个TextView中的文字很长,然后又必须是单行显示,比如下面这句代码:

     
  android:layout_width="wrap_content"
     
  android:layout_height="wrap_content"
     
  android:singleLine="true"
     
  android:text="@string/hello_world" />

就会有这样的显示结果:



后面的文字用...代替了,看不到,现在又希望能够看到,于是有了解决办法便是给TextView加属性:

     
  android:layout_width="wrap_content"
     
  android:layout_height="wrap_content"
     
  android:singleLine="true"
     
  android:ellipsize="marquee"
     
  android:focusable="true"
     
  android:focusableInTouchMode="true"
     
  android:text="@string/hello_world" />




于是文字动起来了,这便是跑马灯了,可是现在开始模拟当这个页面要显示两个TextView的例子,同上述代码加一个TextView再次运行程序:




出现了一种情况就是只有一个TextView跑起来了,原因是焦点不在第二个TextView上,因此不能滚动,怎么解决这个问题呢,现在开始自定义一个类,取名MarqueeTextView,让它继承TextView:

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
@ExportedProperty(category = "focus")
public boolean isFocused() {
return true;
}
}

然后布局文件中用自定义的TextView,只需要把TextView改成com.pyn.test.MarqueeTextView就OK了,于是两个TextView都跑起来了。解决原理最主要就在isFocused()这个方法上,返回true,让每个TextView都能获取到焦点。


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: