Android自定义组合控件

编程入门 行业动态 更新时间:2024-10-26 12:29:05

Android自定义<a href=https://www.elefans.com/category/jswz/34/1769978.html style=组合控件"/>

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自定义组合控件

本文发布于:2023-12-06 02:39:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1666201.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   自定义   控件   Android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!