现在的位置: 首页 > 综合 > 正文

自定义组合控件的方法

2017年11月18日 ⁄ 综合 ⁄ 共 1533字 ⁄ 字号 评论关闭

自定义组合控件

  1)编写一个类继承ViewGroup,

  2)重写构造方法

  3)XML中配置一个视图,控件初始化时,填充这个视图,并挂载到控件中

  4)添加自定义属性

    在value目录中,编写一个xml文件,<?xml version="1.0" encoding="utf-8"?>

<resources>

     <declare-styleable name="setting_view_style">

 <attr name="title" format="string"></attr>

 <attr name="checked_text" format="string"></attr>

 <attr name="unchecked_text" format="string"></attr>

     </declare-styleable>

</resources>

  5)R文件中会自动生成

  6)使用时;需要申请命名控件 xmlns:<随便定义tag>="http://schemas.android.com/apk/res/<包名>"

  8). 在代码的构造方法里面读取自定义的配置.

    //把属性集 和我们自己定义的属性集合建立映射关系

    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.setting_view_style)

 

  9) 通过代码设置读取到信息.

    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.setting_view_style);

String title = a.getString(R.styleable.setting_view_style_title);

checked_text = a.getString(R.styleable.setting_view_style_checked_text);

unchecked_text = a.getString(R.styleable.setting_view_style_unchecked_text);

tv_settingview_content.setText(unchecked_text);

tv_settingview_title.setText(title);

a.recycle();//释放资源.


 

自定义组合控件:

 

 

1. 写一个类 继承ViewGroup 

 

2. 重写构造方法.  

View  view = View.inflate(context, R.layout.ui_setting_view, this);

 

3. 直接在xml或者代码里面就可以使用这个自定义的view对象.

 

 

4. 添加自定义的属性.  values目录 创建declare-styleable  自定义的属性.

在里面创建自定义的attr  (参考sdk里面的定义).

 

 

5. 文件中自动生成我们自己定义的属性的引用.

 

 

6. 声明命名空间 xmlns:<随便定义tag>="http://schemas.android.com/apk/res/<包名>"

 

 

7. tag:attr =""

 

 

8. 在代码的构造方法里面读取自定义的配置.

//把属性集 和我们自己定义的属性集合建立映射关系

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.setting_view_style)

 

9. 通过代码设置读取到信息.


抱歉!评论已关闭.