前言:
在android中我们习惯了在XML布局文件中,进行控件属性的设置,由于控件默认提供的属性数量有限,为了增加属性我们可以给控件添加一些自定义的属性,下面来讲一下为控件添加自定义属性的几个步骤。
什么是自定义属性以及自定义属性的好处:
自定义属性:是指定义可以在布局文件的标签中使用的属性。如TextView控件中的Text属性,但是它是由系统提供的,现如今是由我们自己定义。
好处:这样就可以通过布局xml的方式给视图对象指定自己定义的任意属性值, 而不是仅仅只能使用系统中内定的属性了。
属性值的类型(format)有如下几种:
1、reference 引用类型值 : @id/...2、color 颜色类型值 #ff00ff
3、boolean 布尔类型值 true , false
4、dimension 尺寸类型值 dp / px /sp
5、integer 整数类型值 weight progress max
6、float 浮点型值 0.1f
7、string 字符串类型值 "atrrs"
8、<enum>枚举类型值:水平/垂直
9、flag:位或运算
10、fraction:百分数
1、在res/values文件下添加一个attrs.xml文件:
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyTextView2"> <attr name="myText" format="string"/> <attr name="myTextColor" format="color"/> <attr name="myTextSize" format="dimension"/> </declare-styleable> </resources>
2、在相关的XML布局文件中使用自定义的属性:
在使用了自定义属性的xml布局文件中引用当前应用的命名空间:
eclipse中写成: xmlns:mux="http://schemas.android.com/apk/res/应用包名" ( 其中mux可以任意写 )
android studio中写成: xmlns:mux="http://schemas.android.com/apk/res-auto"
或者 xmlns:mux="http://schemas.android.com/apk/应用包名" ( 其中mux可以任意写)
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:myview="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" ><br> <com.qianmo.activitydetail.MyTextView2 android:layout_width="match_parent" android:layout_height="match_parent" android:background="#00ff00" myview:myText="哈哈哈哈哈哈哈哈哈哈" myview:myTextColor="#ff3399" myview:myTextSize="25sp" /> </LinearLayout>
3、在构造方法中获取自定义的属性值:
public MyTextView2(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs, defStyleAttr); } /** * 初始化数据 */ private void init(Context context, AttributeSet attrs, int defStyleAttr) { //获取自定义属性的值 TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyTextView2, defStyleAttr, 0); mText = a.getString(R.styleable.MyTextView2_myText); mTextColor = a.getColor(R.styleable.MyTextView2_myTextColor, Color.BLACK); mTextSize = a.getDimension(R.styleable.MyTextView2_myTextSize, 30f); a.recycle(); //初始化Paint数据 mPaint = new Paint(); mPaint.setColor(mTextColor); mPaint.setTextSize(mTextSize); //获取绘制的宽高 mBound = new Rect(); mPaint.getTextBounds(mText, 0, mText.length(), mBound); Log.i(TAG, "mText :" + mText + ",mTextColor:" + mTextColor+ ",mTextSize:" + mTextSize); }这样我们就使用上了自定义属性了,快去试试吧。。。