Android自定義控件之TextView


轉自:http://labs.easymobi.cn/?p=284

有時候Android自帶的控件無法滿足我們的某些要求,這時就需要我們自定義控件來實現這些功能。比如需要一個TextView里的字傾斜一定的角度,就需要自定義TextView。

 

右下角的記分牌就是這樣的TextView。

下面介紹怎么自定義TextView。

首先新建一個繼承自TextView的類,取名為RotateTextView:

 1 import  android.content.Context;
 2 import  android.graphics.Canvas;
 3 import  android.util.AttributeSet;
 4 import  android.widget.TextView;
 5 
 6 public  class  RotateTextView  extends  TextView {
 7 private  static  final  String  NAMESPACE = “http://www.ywlx.net/apk/res/easymobi”;
 8 private  static  final  String  ATTR_ROTATE = “rotate”;
 9 private  static  final  int  DEFAULTVALUE_DEGREES = 0;
10 private  int  degrees ;
11 public  RotateTextView(Context context, AttributeSet attrs) {
12 super(context, attrs);
13 degrees = attrs.getAttributeIntValue(NAMESPACE, ATTR_ROTATE, DEFAULTVALUE_DEGREES);
14 
15 }
16 @Override
17 protected  void  onDraw(Canvas canvas) {
18 
19 canvas.rotate(degrees,getMeasuredWidth()/2,getMeasuredHeight()/2);
20 super.onDraw(canvas);
21 }
22 
23 }

 

一定要有帶Context和AttributeSet參數的構造函數,getAttributeIntValue()里第一個參數是命名空間,類似於Android自帶的”http://schemas.android.com/apk/res/android”,這里可以自己隨便定義。第二個參數是傳入的參數的值,這里是旋轉地角度。第三個參數是默認值,就是不定義該屬性時默認旋轉的角度,這里是0度。然后重寫onDraw()方法,rotate()作用是以TextView的中心為中點把畫布旋轉degrees度,這樣就實現了字的旋轉。

下一步就是在布局文件中使用自定義的TextView:

<cn.easymobi.application.memorytest.RotateTextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:padding=”8dip”
android:gravity=”center”
android:id=”@+id/tvBottom_color”
android:textSize=”15dip”
android:textColor=”@color/black”
easymobi:rotate=”10″
android:layout_marginTop=”468dip”
/>

 

其他屬性與普通的TextView相同, easymobi:rotate=”10″指定了旋轉10度,但是要注意在頭文件加上xmlns:easymobi=”http://www.ywlx.net/apk/res/easymobi”,這個就是RotateTextView中的命名空間的作用。還有一點要注意的就是加上合適的padding,因為這種方法旋轉的是TextView里面的字,而不是TextView本身,如果不加padding,有些字就會因為旋轉而跑到了TextView外面而不能顯示。

用類似的方法還可以實現各種各樣你想要的效果。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM