Android实现自定义View

1.创建View类继承View或者View的子类,并继承构造方法。
2.自定义属性

<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--  名字随便起--> 
<declare-styleable name="MyViewStyleName" >
<attr name="des" format="string" />
<attr name="textColor" format="color"/>
<attr name="bgColor" format="color"/>
</declare-styleable>
</resources>

3.构造函数中获取属性,然后就可以使用属性在onDraw中绘画自己的View了,如设置画布背景颜色,字体颜色等

	public MyView(Context context, AttributeSet attrs) {
	super(context, attrs);
	TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.MyViewStyleName);
		if(typedArray != null){
			/**
			 * 获取xml中自定义属性des
			 */
			mDes = typedArray.getString(R.styleable.MyViewStyleName_des);
			/**
			 * 获取xml中自定义属性bgColor
			 */
			mBackground = typedArray.getColor(R.styleable.MyViewStyleName_bgColor, Color.RED);
			/**
			 * 获取xml中自定义属性textColor
			 */
			mTextColor = typedArray.getColor(R.styleable.MyViewStyleName_textColor, Color.WHITE);
	
		}
		//initView();
	}

4.布局中使用自定义的View,并使用自己定义的属性

    <com.example.testdemo.MyView 
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_centerInParent="true"
        app:des="这是自定义View内容"
		app:textColor="#ffffff"
		app:bgColor="#4cd964"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值