自定义组件及属性

来源:互联网 发布:长春自考网络学校 编辑:程序博客网 时间:2024/06/05 17:04

其实很早以前在属性(Attribute)资源的使用:自定义组件一文中就介绍过自定义组件及属性的使用,这里再次回顾以下,直接上代码:

MainActivity:

package com.home.testtypedarray;import android.os.Bundle;import android.app.Activity;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);}}


main布局:

<?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.home.testtypedarray"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <com.home.testtypedarray.MyView        android:layout_width="match_parent"        android:layout_height="match_parent"        test:textColor="#0ff"        test:textSize="20sp" /></LinearLayout>

MyView类:

package com.home.testtypedarray;import android.content.Context;import android.content.res.TypedArray;import android.graphics.Canvas;import android.graphics.Paint;import android.graphics.Paint.Style;import android.graphics.Rect;import android.util.AttributeSet;import android.view.View;public class MyView extends View {private Paint paint;public MyView(Context context, AttributeSet attrs) {super(context, attrs);paint = new Paint();// 得到MyView的TypedArray对象(属性的容器)TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);// 得到MyView的textColor属性值int textColor = a.getColor(R.styleable.MyView_textColor, 0XFFFFFFFF);// 得到MyView的textSize属性值float textSize = a.getDimension(R.styleable.MyView_textSize, 36);paint.setColor(textColor);// 为画笔设置颜色paint.setTextSize(textSize);// 为画笔设置字体大小// Give back a previously retrieved StyledAttributes, for later re-usea.recycle();}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);paint.setStyle(Style.FILL);// 设置为填充风格canvas.drawText("测试自定义属性", 10, 30, paint);// 绘制文字canvas.drawRect(new Rect(10, 50, 200, 200), paint);// 绘制矩形}}

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>