android_Component之自定义组合控件

来源:互联网 发布:内控风险控制矩阵 编辑:程序博客网 时间:2024/05/29 00:30

自定义组合控件实现步骤 :

1. 写一个类 继承ViewGroup 或者 LinearLayout等;

2. 重写构造方法. 
View  view = View.inflate(context, R.layout.ui_setting_view, this);

 注意 : 构造方法有3个,其中1个参数的构造方法是在代码中创建时调用的方法;其他2个是在布局文件中定义使用时调用的方法;

                  一般2个参数的方法调用本地3个参数的方法;

            DefinedView(Context context, AttributeSet attrs, int defStyle);

            DefinedView(Context context, AttributeSet attrs) { this(context,attrs,0); }

            DefinedView(Context context);

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


4. 添加自定义的属性.  values目录 创建declare-styleable  自定义的属性.
在里面创建自定义的attr  (参考sdk里面的定义).android-sdk\platforms\android-10\data\res\values\attrs.xml

          例 :

              <declare-styleable name="homepage_view_style">
                   <attr name="leftName" format="reference|string"></attr>
                   <attr name="leftValue" format="reference|string"></attr>
                   <attr name="rightName" format="reference|string"></attr>
                   <attr name="rightValue" format="reference|string"></attr>
             </declare-styleable>


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


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


7. 在布局文件中使用,tag:attr =""


8. 在代码的构造方法里面读取自定义的配置.
//把属性集 和我们自己定义的属性集合建立映射关系
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.setting_view_style)
使用完毕后,要释放资源
9. 通过代码设置读取到信息.