组合控件"/>
Android自定义组合控件
自定义组合控件为自定义控件中的一种,由已有的控件组合而成。自定义控件类需要继承已有控件(RelativeLayout 、LinearLayout等)
1.组合控件的XML布局文件( res/layout/xxx.xml )
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns: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"/><!-- 属性名 属性值 --><flag name="FLAG_N2" value="1"/></attr></declare-styleable>
</resources>
declare-声明 styleable-风格 attr-属性 flag-标识、标志
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);//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
自定义组合控件需要继承已有控件(RelativeLayout、LinearLayout等)
4.使用自定义组合控件
<MyView android:attrN1="testString"android:attrN2="FLAGN1"... ...
/>
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);}
更多推荐
Android自定义组合控件
发布评论