Android实例-手机安全卫士(四)-主界面增加跑马灯效果文本

一、目标。

  在主页面中增加一个跑马灯效果的显示文本,可用于提示版本更新、广告内容等。

效果如图:

二、代码实现。

  1、在src文件下新建包(取名com.example.mobilesafe.ui),用于存放自定义的类。

  2、在该包下新建类(取名MarqueeTextView)继承TextView,用于实现跑马灯效果。(跑马灯效果实现的思路主要是借鉴Button组件,Button通过设置focusableInTouchMode属性和singleLine属性为true、ellipsize属性值为marquee时便可实现跑马灯效果,因此通过新建一个组件(MarqueeTextView),设置相同属性时就可实现同样效果,即让新组件创建时便获取焦点)。

    ①.在新建类(MarqueeTextView)代码中从超类中生成构造函数。点击菜单栏中的“Source”,从弹出的列表项中选择Generate Constructors from Superclass,在弹出的对话框中点击OK,从而自动生成三个构造函数。同时复写isFocused()方法,并将其返回值设为true,以保证新建的组件创建时就有焦点。复写方式:右键——Override....,在弹出的对话框中缩略TextView,展开View,找到其中的isFocused()方法,点击Ok。

复写isFocused()方法代码;

1 @Override
2     @ExportedProperty(category = "focus")
3     public boolean isFocused() {        
4         return true;
5     }
View Code

    ②.其余都无需更改。

新建类(MarqueeTextView)代码如下:

 1 public class MarqueeTextView extends TextView {
 2 
 3     public MarqueeTextView(Context context, AttributeSet attrs, int defStyle) {
 4         super(context, attrs, defStyle);        
 5     }
 6 
 7     public MarqueeTextView(Context context, AttributeSet attrs) {
 8         super(context, attrs);        
 9     }
10 
11     public MarqueeTextView(Context context) {
12         super(context);        
13     }
14 
15     @Override
16     @ExportedProperty(category = "focus")
17     public boolean isFocused() {        
18         return true;
19     }
20 }
View Code

    ③.拷贝新建类的全路径,在主界面布局文件中,在TextView和GridView之间增加一个新建类的控件,设置设置singleLine属性为true、ellipsize属性值为marquee时便可实现跑马灯效果。无需设置focusableInTouchMode属性,因为在创建该组件时就保证其有焦点。

增加新建类控件的代码;

1 <com.example.mobilesafe.ui.MarqueeTextView
2         android:focusableInTouchMode="true"
3         android:layout_width="match_parent"
4         android:layout_height="wrap_content"
5         android:ellipsize="marquee"
6         android:singleLine="true"
7         android:text="手机卫士有新版本!!    手机卫士有新版本!!    手机卫士有新版本!!手机卫士有新版本!!"
8         android:textSize="14sp" />
View Code
posted @ 2015-01-22 15:02  红烧大白鲨  阅读(315)  评论(0编辑  收藏  举报