android自定义控件

根据需要,我这里实现了一个TextView控件的增强。

1、增加版控件的类定义

 1 package com.xx.android;
 2 
 3 import android.content.Context;
 4 import android.graphics.Color;
 5 import android.os.Handler;
 6 import android.os.Message;
 7 import android.util.AttributeSet;
 8 import android.widget.TextView;
 9 
10 public class MyTextView extends TextView {
11 
12     private String  strValue = ""; 
13     public static final int GUIUPDATEIDENTIFIER = 0x000000;
14     public MyTextView(Context context) {
15         super(context);
16         //this.setTextColor(Color.BLUE);
17         //new Thread(new myThread()).start();
18     }
19     public MyTextView(Context context, AttributeSet attrs){
20         super(context, attrs);
21         this.setTextColor(Color.RED);
22         new Thread(new myRunable()).start();
23         strValue = MyTextView.this.getText().toString();
24     }
25     public MyTextView(Context context, AttributeSet attrs, int defStyle){
26         super(context, attrs, defStyle);
27         //this.setTextColor(Color.BLUE);
28         //new Thread(new myThread()).start();
29     }
30     Handler handler = new Handler(){
31         public void handleMessage(Message msg) {   
32             switch (msg.what) {   
33             case MyTextView.GUIUPDATEIDENTIFIER:   
34                 String str = MyTextView.this.getText().toString();
35                 if(!str.equals("")){
36                     str = str.subSequence(1, str.length()).toString();
37                     MyTextView.this.setText(str);
38                 }
39                 else {
40                     MyTextView.this.setText(strValue);
41                 }
42                 break; 
43             default:
44 
45             }   
46             super.handleMessage(msg);   
47         }   
48     };
49     
50     class myRunable implements Runnable {   
51         public void run() {  
52             while (!Thread.currentThread().isInterrupted()) {    
53 
54                 Message message = new Message();   
55                 message.what = MyTextView.GUIUPDATEIDENTIFIER;   
56 
57                 MyTextView.this.handler.sendMessage(message);   
58                 try {   
59                     Thread.sleep(500);    
60                 } catch (InterruptedException e) {   
61                     Thread.currentThread().interrupt();   
62                 }   
63             }   
64         }   
65     }   
66 }

2、在对应布局xml文件中,像定义一般组件一样定义该控件。

1 <!-- 我是在main.xml文件定义的-->
2 <com.xx.android.MyTextView
3         android:layout_width="fill_parent"
4         android:layout_height="wrap_content"
5         android:text="@string/str"
6         android:textSize="30dp">
7     </com.xx.android.MyTextView>

效果图:【注意,这里的截图的红色部分是会滚动的,不知道怎么截动画,所有没有给出动画图】

原文地址:https://www.cnblogs.com/xuxu8511/p/2548112.html