读取layout属性-AttributeSet TypedArray
发布日期:2021-09-30 11:34:34
浏览次数:6
分类:技术文章
本文共 2055 字,大约阅读时间需要 6 分钟。
假如说要读取layout_height属性
两种方式,第一种
/** * Returns the value of the specified attribute as a string representation. * * @param index Index of the desired attribute, 0...count-1. * * @return A String containing the value of the attribute, or null if the * attribute cannot be found. */ public String getAttributeValue(int index);String namespace = "http://schemas.android.com/apk/res/android";viewHeight = attrs.getAttributeIntValue(namespace, "layout_height", ViewGroup.LayoutParams.MATCH_PARENT);
layout_height=“match_parent”
viewHeight 取到的值为 “match_parent”
layout_height=“100dip”
viewHeight 取到的值为 “100dip”
如果用 getAttributeIntValue 读取的话, 无法正确读取到数值
/** * Return the integer value of 'attribute'. * * @param namespace Namespace of attribute to retrieve. * @param attribute The attribute to retrieve. * @param defaultValue What to return if the attribute isn't found. * * @return Resulting value. */ public int getAttributeIntValue(String namespace, String attribute, int defaultValue);
很显然这种方式读取数值不是很爽
第二种方式: 通过TypedArray读取
int[] arr = new int[] { android.R.attr.layout_width, android.R.attr.layout_height }; TypedArray typedArray = context.obtainStyledAttributes(attrs, arr); // MATCH_PARENT -1 WRAP_CONTENT-2 try { // String namespace = "http://schemas.android.com/apk/res/android"; // initViewHeight = attrs.getAttributeIntValue(namespace, "layout_height", ViewGroup.LayoutParams.MATCH_PARENT); TypedValue typeValue = typedArray.peekValue(1); if (typeValue.type == TypedValue.TYPE_DIMENSION) {// 0x10 initViewHeight = (int) typedArray.getDimension(1, ViewGroup.LayoutParams.MATCH_PARENT); initViewHeight = TypedValue.complexToDimensionPixelSize(typeValue.data, getResources().getDisplayMetrics()); } else if (typeValue.type == TypedValue.TYPE_FIRST_INT) {// 0x05 initViewHeight = typeValue.data; } } catch (Exception e) { // java.lang.UnsupportedOperationException: Can't convert to dimension: type=0x10 e.printStackTrace(); } typedArray.recycle();
转载地址:https://blog.csdn.net/id19870510/article/details/52982527 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
做的很好,不错不错
[***.243.131.199]2024年04月07日 15时13分58秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
NetBeans配置Xdebug 远程调试PHP
2019-04-27
MediaWiki安装
2019-04-27
Squid安装
2019-04-27
如何查看当前Linux的版本
2019-04-27
Ubuntu安装Nginx
2019-04-27
Ubuntu 下安装thttpd Web服务器
2019-04-27
用thttpd做Web Server
2019-04-27
服务器端开发经验总结 Linux C语言
2019-04-27
将网站程序放在tmpfs下
2019-04-27
使用Nginx的proxy_cache缓存功能取代Squid
2019-04-27
nginx 反向代理,动静态请求分离,proxy_cache缓存及缓存清除
2019-04-27
nginx 的proxy_cache才是王道
2019-04-27
Nginx proxy_cache 使用示例
2019-04-27
Nginx源代码分析 - 日志处理
2019-04-27
使Apache实现gzip压缩
2019-04-27
Memcached在大型网站中应用
2019-04-27
Hadoop简要介绍
2019-04-27
squid中的X-Cache和X-Cache-Lookup的意义
2019-04-27
squid 优化指南
2019-04-27
编程方式刷新Squid缓存服务器的五种方法
2019-04-27