一、前言
Demo地址 https://github.com/LPLuck/CustomView.git
对于自定义属性,我想新手一定是云里雾里吧,看了几遍博客,感觉写的有点复杂,我就根据自己的使用简单的写个用法和步骤吧。
二、步骤
1、 自定义一个CustomView(extends View )类,这个就不需要讲了吧,直接新建一个就行
2、编写values/attrs.xml,在其中编写styleable和item等标签元素
<resources> <!--定义名字叫CustomAttributeView的属性集合--> <declare-styleable name="CustomAttributeView"> <!--定义一个名字叫my_name并且类型是string的属性--> <attr name="my_name" format="string"/> <!--定义一个名字叫my_age并且类型是integer的属性--> <attr name="my_age" format="integer"/> <!--定义一个名字叫my_bg并且类型是reference|color的属性--> <attr name="my_bg" format="reference|color"/> </declare-styleable> </resources>
format 常用类型
- reference 引用
- color 颜色
- boolean 布尔值
- dimension 尺寸值
- float 浮点值
- integer 整型值
- string 字符串
- enum 枚举
3、在布局文件中CustomView使用自定义的属性(注意namespace,命名空间)
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.liupeng.lp.customview.MainActivity"> <com.liupeng.lp.customview.CustomAttributeView android:layout_width="wrap_content" android:layout_height="wrap_content" app:my_name="lp" app:my_age="20" app:my_bg="@mipmap/ic_launcher"/> </RelativeLayout>app这个名字可以自己修改,一般是叫app
4、在CustomView的构造方法中通过TypedArray获取,有三种方法得到属性值。
public class CustomAttributeView extends View { private String myName; private int myAge; private String myBg; private Bitmap bgBitmap; public CustomAttributeView(Context context, AttributeSet attrs) { super(context, attrs); //获取属性的三种方式 //1.用命名空间获取 // myName = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto","my_name"); // myAge = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto","my_age"); // myBg = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto","my_bg"); // System.out.println("myName="+myName+"myAge="+myAge+"myBg="+myBg); // 2.遍历属性集合 // for(int i=0;i<attrs.getAttributeCount();i++){ // System.out.println(attrs.getAttributeName(i)+"=="+attrs.getAttributeValue(i)); // } //3.使用系统工具 TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomAttributeView); final int N = typedArray.getIndexCount(); for (int i = 0; i < N; i++) { int attr = typedArray.getIndex(i); switch (attr) { case R.styleable.CustomAttributeView_my_name: myName = typedArray.getString(attr); break; case R.styleable.CustomAttributeView_my_age: myAge = typedArray.getInt(attr, 0); break; case R.styleable.CustomAttributeView_my_bg: Drawable drawable = typedArray.getDrawable(attr); BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; bgBitmap = bitmapDrawable.getBitmap(); break; } }array.recycle();} @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint = new Paint(); canvas.drawText(myName+"===="+myAge,50,50,paint); canvas.drawBitmap(bgBitmap,50,50,paint); }
Demo地址 https://github.com/LPLuck/CustomView.git