Android中TextView不获取焦点可以实现跑马灯的效果

第一种:

[java]  view plain  copy
  1. Animation ani = new TranslateAnimation(310f, -400f, 0.0f, 0.0f);  
  2. ani.setDuration(10000);  
  3. ani.setRepeatCount(500);  
  4. ani.setRepeatMode(1);  
  5. TextView textView =(TextView) this.findViewById(R.id.text);  
  6. textView .startAnimation(ani);  

第二种:

我通过网上的一些例子自己在做了一些改动,就实现了现在不用获取焦点也能“跑”起来的效果。

首先,写一个类,让其继承自TextView:

  
  
[java] view plain copy
在CODE上查看代码片 派生到我的代码片
  1. public class MarqueeText extends TextView {  
  2.  public MarqueeText(Context con) {  
  3.  super(con);  
  4. }                                      
  5. public MarqueeText(Context context, AttributeSet attrs) {  
  6. super(context, attrs);  
  7. }  
  8. public MarqueeText(Context context, AttributeSet attrs, int defStyle) {  
  9. super(context, attrs, defStyle);  
  10. }  
  11. @Override  
  12. public boolean isFocused() {  
  13. return true;  
  14. }  
  15. @Override  
  16. protected void onFocusChanged(boolean focused, int direction,  
  17. Rect previouslyFocusedRect) {  
  18. }  
  19. }  

然后再将我们已经写好的这个控件(MarqueeText)放到布局文件中,例如main.xml:

<!-- 在布局文件中用自己写的控件只需要写类的全名就行,如下com.example这是包名,后面再跟类名就行了 -->
  
  
[html] view plain copy
在CODE上查看代码片 派生到我的代码片
  1. <com.example.MarqueeText  
  2. android:id="@+id/AMTV1"  
  3. android:layout_width="400dip"  
  4. android:layout_height="wrap_content"  
  5. android:layout_marginLeft="80dip"  
  6. android:textSize="25sp"  
  7. android:textColor="@android:color/black"  
  8. android:lines="1"  
  9. android:focusable="true"  
  10. android:focusableInTouchMode="true"  
  11. android:scrollHorizontally="true"  
  12. android:marqueeRepeatLimit="marquee_forever"  
  13. android:ellipsize="marquee"  
  14. android:background="#2FFFFFFF"  
  15. android:text="这才是真正的文字跑马灯效果,文字移动速度,文字移动方向,文字移动的样式,动画等等……"  
  16. />  

关于MarqueeText类中为什么要复写onFocusChanged()方法,那是因为如果不写,在Textview 获得焦点后,再失去焦点时字就会停止“跑”了,所以如果想让它一直跑下去就复写onFocusChanged(),并且里面什么也不做(主要是不能调用父类的方法)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值