自定义组合控件为自定义控件中的一种,由已有的控件组合而成。自定义控件类需要继承已有控件(RelativeLayout 、LinearLayout等)
1.组合控件的XML布局文件( res/layout/xxx.xml )
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</RelativeLayout>
2.设置组合控件的属性的XML文件 ( res/value/attrs.xml )
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- 声明-风格 自定义控件名-->
<declare-styleable name="MyView">
<attr name="attrN1" format="string"/>
<!-- 属性名 属性类型 -->
<attr name="attrN2">
<flag name="FLAG_N1" value="1"/>
<!-- 属性名 属性值(此值只能为int) -->
<flag name="FLAG_N2" value="1"/>
</attr>
</attr name="attrN3" format="reference"/>
<!-- 属性名 属性值(资源R.~.~) -->
</declare-styleable>
</resources>
declare-声明 styleable-风格 attr-属性 flag-标识、标志
format="reference"标识类型为资源 ( R.~.~ )
3.创建自定义组合控件类( app / java / 包名 / xxx.java )
public class MyView extends RelativeLayout { //继承已有控件(RelativeLayout、LinearLayout等)
private int i;
private TextView textView;
public MyView(Context context) {
super(context);
//用于Java文件中的构造函数
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
//用于XML布局文件中的构造函数
getAttrs(context,attrs);
setView(context);
}
private void getAttrs(Context context,AttributeSet attrs){
//获取属性值
TypedArray typedArray=context.obtainStyledAttributes(attrs,R.styleable.MyView);
i=typedArray.getInt(R.styleable.MyView_attrN2,1);
int id=typedArray.getResourceId(R.styleable.MyView_attrN3,R.~.~);
//typedArray.getString typedArray.getBoolean
//回收
typedArray.recycle();
}
private void setView(Context context){
LayoutInflater.from(context).inflate(R.layout.myview,this);
textView=(TextView) findViewById( ~ );
textView.setText(i);
}
}
获取自定义控件属性值以后一定要回收TypedArray
使用getResourceId()获取类型为reference的资源ID
自定义组合控件需要继承已有控件(RelativeLayout、LinearLayout等)
LayoutInflater.from( context ).inflate( R.layout.myview , this ); 根为this
4.使用自定义组合控件
<MyView
app:attrN1="testString"
app:attrN2="FLAGN1"
... ...
/>
自定义属性使用: app: 属性名 = " 属性值 "
5.注:自定义控件类需实现方法
public class MyView extends RelativeLayout {
public MyView(Context context) {
super(context);
//用于Java文件中的构造函数
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
//用于XML布局文件中的构造函数
TypedArray ta=context.obtainStyledAttributes(attrs,R.styleable.MyView);
LayoutInflater.from(context).inflate(R.layout.myview,this);
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//该方法用于测量尺寸,在该方法中可以设置控件本身或其子控件的宽高
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//该方法用于绘制图像
}
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
//用于指定布局中子控件的位置
}
}