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>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值