android 自定义属性实现过程

 

自定义View属性过程总结

1、  首先创建一个继承自View或其它widget的类,例如:MyLayout.java

public class MyLayout extends View{

private Paint mPaint;

public MyLayout(Context context, AttributeSet attrs,            int defStyle) {

      super(context, attrs, defStyle);

      // TODO Auto-generated constructor stub

   }

   public MyLayout(Context context, AttributeSet attrs) {

      super(context, attrs);

      // TODO Auto-generated constructor stub

      mPaint = new Paint();

      TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyLayout);

 

  int textColor = array.getColor(R.styleable.MyLayout_textColor, 0XFF00FF00); //提供默认值,放置未指定

   float textSize = array.getDimension(R.styleable.MyLayout_textSize, 36);

      mPaint.setColor(textColor);

      mPaint.setTextSize(textSize);

      array.recycle();

   }

   public MyLayout(Context context) {

      super(context);

      // TODO Auto-generated constructor stub

   }

   public void onDraw(Canvas canvas){

      super.onDraw(canvas);

      //Canvas中含有很多画图的接口,利用这些接口,我们可以画出我们想要的图形

      //mPaint = new Paint();

      //mPaint.setColor(Color.RED);

      mPaint.setStyle(Style.FILL); //设置填充

      canvas.drawRect(10, 10, 100, 100, mPaint); //绘制矩形

      mPaint.setColor(Color.BLUE);

      canvas.drawText("我是被画出来的", 10, 120, mPaint);

      }

}

2、  在values下创建attrs的xml文件,用于存放view的属性。

<?xml version="1.0" encoding="utf-8"?>

<resources>

    <declare-styleable name="MyLayout">

    <attr format="color" name="textColor"/> 

    <attr format="dimension" name="textSize"/>

    </declare-styleable>

</resources>

3、  在布局文件中包含创建好的属性。

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"          xmlns:my="http://schemas.android.com/apk/res/com.ghong.mylayout"

    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.ghong.mylayout.MyLayout

      android:layout_width="fill_parent" 

      android:layout_height="wrap_content"   

      my:textColor="#FFFFFFFF"   

      my:textSize="22dp" 

    />

</LinearLayout>

 

posted @ 2011-09-28 19:45  你好and程序员  阅读(98)  评论(0编辑  收藏  举报