本文主要是介绍无鸯 Android中自定义属性(attrs.xml,TypedArray)的使用,,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
这个例子比较全,很不错,
转自 http://www.oschina.net/code/snippet_163910_6283
package com.adnroid.test;
03 | import com.adnroid.test.R; |
05 | import android.content.Context; |
06 | import android.content.res.TypedArray; |
07 | import android.graphics.Canvas; |
08 | import android.graphics.Color; |
09 | import android.graphics.Paint; |
10 | import android.graphics.Rect; |
11 | import android.graphics.Paint.Style; |
12 | import android.util.AttributeSet; |
13 | import android.view.View; |
15 | public class MyView extends View { |
16 | private Paint myPaint; |
17 | private static final String myString = "Welcome to our Zoon!"; |
19 | public MyView(Context context) { |
24 | public MyView(Context context, AttributeSet attr) { |
26 | myPaint = new Paint(); |
27 | TypedArray a = context.obtainStyledAttributes(attr, R.styleable.myView); |
28 | float textSize = a.getDimension(R.styleable.myView_textSize, 30); |
29 | int textColor = a.getColor(R.styleable.myView_textColor, 0xFFFFFFFF); |
30 | myPaint.setTextSize(textSize); |
31 | myPaint.setColor(textColor); |
35 | protected void onDraw(Canvas canvas) { |
39 | myPaint.setColor(Color.RED); |
40 | myPaint.setStyle(Style.FILL); |
42 | canvas.drawRect(new Rect(10,10,100,100), myPaint); |
43 | myPaint.setColor(Color.WHITE); |
44 | canvas.drawText(myString, 10, 100, myPaint); |
2. [代码]attrs.xml
1 | <?xml version="1.0" encoding="utf-8"?> |
3 | <declare-styleable name="myView"> |
4 | <attr name="textColor" format="color"/> |
5 | <attr name="textSize" format="dimension"/> |
3. [代码]main.xml
01 | <?xml version="1.0" encoding="utf-8"?> |
02 | <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" |
03 | xmlns:test="http://schemas.android.com/apk/res/com.adnroid.test" |
04 | android:orientation="vertical" |
05 | android:layout_width="fill_parent" |
06 | android:layout_height="fill_parent" |
09 | android:layout_width="fill_parent" |
10 | android:layout_height="wrap_content" |
11 | android:text="@string/hello" |
13 | <com.adnroid.test.MyView |
14 | android:layout_width="fill_parent" |
15 | android:layout_height="fill_parent" |
4. [图片] 6c32391db1a8d7cd86d6b6bc.jpg.png
这篇关于无鸯 Android中自定义属性(attrs.xml,TypedArray)的使用,的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!