安卓 --自定义控件 添加属性。。

安卓自定义控件 添加属性

一、在res/values文件下定义一个attrs.xml文件.代码如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyView">
        <attr name="textColor" format="color" />
        <attr name="textSize" format="dimension" />
    </declare-styleable>
</resources>

<attr name="textSize" format="dimension" />  其中,name是 自定义属性值  format是属性的数据类型。 

http://wiseideal.iteye.com/blog/1481559

自定义控件类

1.package com.android.tutor; 
2.import android.content.Context; 
3.import android.content.res.TypedArray; 
4.import android.graphics.Canvas; 
5.import android.graphics.Color; 
6.import android.graphics.Paint; 
7.import android.graphics.Rect; 
8.import android.graphics.Paint.Style; 
9.import android.util.AttributeSet; 
10.import android.view.View; 
11.public class MyView extends View { 
12.private Paint mPaint; 
13.private Context mContext; 
14.private static final String mString = "Welcome to Mr Wei's blog"; 
15. 
16.public MyView(Context context) { 
17.super(context); 
18.mPaint = new Paint(); 
19.} 
20.public MyView(Context context,AttributeSet attrs) 
21.{ 
22.super(context,attrs); 
23.mPaint = new Paint(); 
24. 
25.TypedArray a = context.obtainStyledAttributes(attrs, 
26.R.styleable.MyView); 
27. 
28.int textColor = a.getColor(R.styleable.MyView_textColor, 
29.0XFFFFFFFF); 
30.float textSize = a.getDimension(R.styleable.MyView_textSize, 36); 
31. 
32.mPaint.setTextSize(textSize); 
33.mPaint.setColor(textColor); 
34. 
35.a.recycle(); 
36.} 
37.@Override 
38.protected void onDraw(Canvas canvas) { 
39.// TODO Auto-generated method stub 
40.super.onDraw(canvas); 
41.//设置填充 
42.mPaint.setStyle(Style.FILL); 
43. 
44.//画一个矩形,前俩个是矩形左上角坐标,后面俩个是右下角坐标 
45.canvas.drawRect(new Rect(10, 10, 100, 100), mPaint); 
46. 
47.mPaint.setColor(Color.BLUE); 
48.//绘制文字 
49.canvas.drawText(mString, 10, 110, mPaint); 
50.} 
51.} 
View Code

" xmlns:test ="http://schemas.android.com/apk/res/com.android.tutor" ,test是自定义属性的前缀, com.android.tutor是我们包名(自定义控件所在包).

<?xml 
version="1.0" encoding="utf-8"?>
<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
              
xmlns:test="http://schemas.android.com/apk/res/com.android.tutor"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<com.android.tutor.MyView
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    test:textSize="20px"
    test:textColor="#fff"
/>
</LinearLayout>
View Code

 

posted on 2014-12-25 16:56  Top@Gragon  阅读(278)  评论(0)    收藏  举报

导航