android_Component之自定义组合控件

本文详细介绍了如何在Android中自定义组合控件,包括继承ViewGroup、重写构造方法、在XML中使用自定义View、添加自定义属性、读取属性值等关键步骤。通过这些步骤,开发者可以灵活地创建符合项目需求的个性化组件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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. 通过代码设置读取到信息.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值