TextView,Button等字体的循环滚动

来源:互联网 发布:剑元上至 知乎 编辑:程序博客网 时间:2024/05/16 10:00

下面是三种不同的按钮布局,分别实现了一般按钮、滚动一次和无限滚动效果。

A、一般按钮

<Button 
android:layout_width="150px" 
android:layout_height="wrap_content" 
android:text="按钮" 
android:singleLine="true" 
android:ellipsize="marquee" 
/>

B、按钮上的文字滚动一次

<Button 
android:layout_width="150px" 
android:layout_height="wrap_content" 
android:text="滚动一次的按钮" 
android:singleLine="true" 
android:ellipsize="marquee" 
android:marqueeRepeatLimit="1" 
/>

C、按钮上的文字循环滚动

<Button 
android:layout_width="150px" 
android:layout_height="wrap_content" 
android:text="循环滚动文字的按钮" 
android:singleLine="true" 
android:ellipsize="marquee" 
android:marqueeRepeatLimit="marquee_forever" 
/>

由以上布局信息可以看出,ellipsize属性设置的是该按钮上内容为可滚动,而marqueeRepeatLimit则设定滚动的模式。



跑马灯效果最重要的就是四个属性,分别是:

android:ellipsize="marquee"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:singleLine="true"

控件的宽度,不一定是具体的值,可以是math_parent,如果想让textview中的文字滚动的话,那里面内容的长度肯定是要大于控件的长度的,不然滚动还有啥意思..

不过这样写的话,虽然很简单.但是有一个问题.就是只有在控件获得到焦点的时候才可以滚动.如果我们在textview控件的下方,添加一个edittext,直接就回看到用这四个属性修饰的.刚刚那个还可以滚动的textview现在竟然一动不动了.这个时候我们就要来对textview进行自定义了


[java] view plaincopy
  1. package com.example.testscrotextview;  
  2.   
  3. import android.content.Context;  
  4. import android.graphics.Rect;  
  5. import android.util.AttributeSet;  
  6. import android.widget.TextView;  
  7.   
  8. public class MyScrollTextView extends TextView {  
  9.   
  10.     public MyScrollTextView(Context context, AttributeSet attrs) {  
  11.         super(context, attrs);  
  12.     }  
  13.   
  14.     public MyScrollTextView(Context context) {  
  15.         super(context);  
  16.     }  
  17.       
  18.     @Override  
  19.     public boolean isFocused() {  
  20.         return true;//直接让他一直是获得焦点状态  
  21.     }  
  22.       
  23.       
  24.     @Override  
  25.     public void onWindowFocusChanged(boolean hasWindowFocus) {  
  26.         if(hasWindowFocus)//获得焦点的时候,才执行一些操作  
  27.         super.onWindowFocusChanged(hasWindowFocus);  
  28.     }  
  29.   
  30.     @Override  
  31.     protected void onFocusChanged(boolean focused, int direction,  
  32.             Rect previouslyFocusedRect) {  
  33.         if(focused)//获得焦点的时候,才执行一些操作  
  34.         super.onFocusChanged(focused, direction, previouslyFocusedRect);  
  35.     }  
  36.       
  37. }  

0 0
原创粉丝点击