前言:
Android控件可以分为:组合控件和原生控件。
举例:组合控件----像广告条控件就是组合控件:它由:ViewPager和一些布局组合而成。
原生控件----继承View、ViewGroup 或继承现有的控件
自定义控件的两种方法:
一、1.写一个继承自View的类
2.在布局文件中引用该自定义控件
3.在自定义控件中加入自定义属性
<com.lcj.view.ImageAndText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
Text = "@string/lcj"
Src = "@drawable/b"/>
4.在自定义的类中的构造方法中写如下:
public ImageAndText(Context context, AttributeSet attrs) {
super(context, attrs);
//返回对应属性资源的ID
textId = attrs.getAttributeResourceValue(null, "Text", 0);
srcId = attrs.getAttributeResourceValue(null, "Src", 0);
}
5.之后在ondraw中根据textId和srcId获取到具体的资源并画在界面上
二、1.写一个继承自View的类
2.自定义控件的属性:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr name="textColor" format="color" />
<attr name="textSize" format="dimension" />
</declare-styleable>
</resources>
其中format可以是:reference string color dimension boolean integer float fraction enum flag
3.在自定义类中的构造方法中获取到布局文件中的数据
public ImageAndText2(Context context, AttributeSet attrs) {
super(context, attrs);
//获取自定义属性的数组
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyView);
//从typeArray数组中获取到自定义的颜色属性---默认是红色
int textColor = typedArray.getColor(R.styleable.MyView_textColor, Color.RED);
//从typeArray数组中获取到自定义的字体大小属性---默认是15
float textSize = typedArray.getDimension(R.styleable.MyView_textSize, 15);
paint = new Paint();
paint.setTextSize(textSize);
paint.setColor(textColor);
//保持以后使用该属性一致性
typedArray.recycle();
}
4.在onDraw方法中进行绘制。
注意:
1、如果自定义的view是直接放在layout布局文件中应用的话,则其构造函数中一定有包含Attributes类型参数,否则付出Error inflate……错误
3、AttributeSet中封装了布局文件中控件的属性。