自定义View应该怎么定义
来源:互联网 发布:网络视频自己组装枪支 编辑:程序博客网 时间:2024/05/18 13:24
android自定义view组件不可避免。那么如何才能做到像官方提供的那些组件一样用xml来定义他的属性呢?废话不多说。
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="ToolBar"> <attr name="buttonNum" format="integer"/> <attr name="itemBackground" format="reference|color"/> </declare-styleable> </resources>
二、在布局xml中如下使用该属性:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:toolbar="http://schemas.android.com/apk/res/cn.zzm.toolbar" // 这里注意后面cn.zzm.toolbar这路径,此路径是你定义的ToolBar类的路径 android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <cn.zzm.toolbar.ToolBar //自定义的view的路径 ToolBar类android:id="@+id/gridview_toolbar" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:background="@drawable/control_bar" android:gravity="center" toolbar:buttonNum="5" //这个属性就是我们在res/values下的attrs.xml中定义的属性 注意格式哦 toolbar:itemBackground="@drawable/control_bar_item_bg"/> //同上</RelativeLayout>
如果你要对自定义的属性要在自定义view类中进行计算等,那么在自定义组件中,可以如下获得xml中定义的值:
public ToolBar(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);roundWidth = DensityUtil.dip2px(context, 3); roundHeight = DensityUtil.dip2px(context, 3);// 获取xml中定义的属性TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.ToolBar); buttonNum = a.getInt(R.styleable.ToolBar_buttonNum, 5); itemBg = a.getResourceId(R.styleable.ToolBar_itemBackground, -1);a.recycle();}
本文借鉴了 http://blog.csdn.net/hnjb5873/article/details/41675543
1 0
- 自定义View应该怎么定义
- Android自定义View--定义属性
- Android 自定义View 一般View定义
- 自定义View应该明白的基础知识
- Android 自定义View format 属性定义
- Android 自定义View-怎么绘制居中文本?
- Android 自定义View-怎么绘制居中文本?
- Android自定义View研究(四) -- 在XML中定义View
- Android自定义View研究(四) -- 在XML中定义View
- 自定义View---怎么解决View的滑动冲突
- 【Android自定义View实战】之你应该明白的事儿
- TreeSet 存储自定义类型时CompareTo 方法应该怎么写
- 自定义View如何定义和使用自己的属性
- 自定义布局执行流程之 画出自己定义的View
- 自定义布局执行流程之 画出自己定义的View
- 自定义控件 继承View 使用OnMeasure定义控件宽高
- 自定义View之定义一个简化版的TextView
- Android自定义View-------为什么重写onMeasure()以及怎么重写
- iOS认知,学好iOS基本要学习什么
- CCS5安装及配置注意事项
- SQL CREATE INDEX 语句
- 工作中常常使用的几种加密以及签名的方式:DES加密
- java-JVM中对象判活
- 自定义View应该怎么定义
- RxJava操作符系列一
- 【iOS开发】使用Xcode8 添加Launch Image(启动图片)之001
- Java 动态代理作用是什么 ==AOP?
- SQL 撤销索引、表以及数据库
- Mybatis分页拦截器
- 开灯问题
- js对象中什么是可枚举性(enumerable)?
- 快速排序