我想像源码那样定义属性,在layout中控制,在Style中控制,
1)自定义属性(上一篇中两个参数(defStyleAttr 和defStyleRes)这一篇还是没用到,下一篇再用 )
第一步:在values-文件夹下新建attrs.mxl 如下代码
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyCustomAttrs">
<attr name="mytextcolor" format="color"/>
<attr name="mybackground" format="reference"/>
<attr name="mytextsize" format="dimension"/>
<attr name="mytext" format="string"/>
</declare-styleable>
</resources>
这里我定义了一个属性集 MyCustomAttrs,包含该下级属性四个,这里的format表示的是这个属性是哪一种类型, reference表示一种通用的(我这样理解),有些图片什么的可以使用这个类型
第二步:自定义View,代码如下
public class MyTextView extends TextView {
private String TAG = "MyTextView";
public MyTextView(Context context) {
this(context, null);
}
public MyTextView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public MyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public MyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomAttrs, defStyleAttr, defStyleRes);
float dimension = a.getDimension(R.styleable.MyCustomAttrs_mytextsize,0);
int color = a.getColor(R.styleable.MyCustomAttrs_mytextcolor, Color.BLACK);
Drawable drawable = a.getDrawable(R.styleable.MyCustomAttrs_mybackground);
String str = a.getString(R.styleable.MyCustomAttrs_mytext);
setText(str);
setTextColor(color);
setTextSize(dimension);
setBackground(drawable);
a.recycle();
}
}
就像上一篇源码里一样获取属性,并且使用获得的属性值
第三步:在布局XML中赋值属性,(注意)自定义一个名称空间,这样使用就会默认使用到自己的包内的属性而不是源码里的属性了。
名称空间方式1,表示res资源使用自动的,当前的应用程序包下的
xmlns:myxmlspace="http://schemas.android.com/apk/res-auto"
名称空间方式2,表示res资源使用指定的包名,这里我指定的就是自己的应用程序
xmlns:myxmlspace="http://schemas.android.com/apk/res/demo.qin.xue.com.customattr"
在布局里使用这些属性
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myxmlspace="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<demo.qin.xue.com.customattr.MyTextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:gravity="center"
myxmlspace:mytextcolor ="@android:color/holo_red_light"
myxmlspace:mybackground ="@mipmap/ic_launcher"
myxmlspace:mytextsize = "50dp"
myxmlspace:mytext = "HELLO WORLD" />
</RelativeLayout>
运行下来:效果如下,属性全部应用到了TextView上面
http://download.youkuaiyun.com/detail/qinxue24/9855389