
有时候我们需要把颜色,数值写成attr属性,这样做是为了屏蔽开发者对应具体数值,比如我们需要设置不同主题下的主色,副色,或者是不同版本的ActionBar大小,亦或者是不同Dpi下的DrawerLayout的宽度等。
在xml里,我们可以简单的引用attr属性值,例如:
android:background="attr/colorPrimary"
android:minHeight="attr/actionBarSize"
当然,我们有时候也需要在代码中获取attr属性值:
TypedValue typedValue = new TypedValue();
contextgetTheme()resolveAttribute(RattryourAttr, typedValue, true);
// For string
typedValuestring
typedValuecoerceToString()
// For other data
typedValueresourceId
typedValuedata;
获取arrt样式中的值
以上是针对个体数值根据不同类型来获取的,如果想要获取 style 的话,需要在拿到 resourceId 之后再进一步获取具体数值,以 TextAppearanceLarge 为例:
<style name="TextAppearanceLarge">
<item name="android:textSize">22sp</item>
<item name="android:textStyle">normal</item>
<item name="android:textColor">textColorPrimary</item>
</style>
TypedValue typedValue = new TypedValue();
contextgetTheme()resolveAttribute(androidRattrtextAppearanceLarge, typedValue, true);
int[] attribute = new int[] { androidRattrtextSize };
TypedArray array = contextobtainStyledAttributes(typedValueresourceId, attribute);
int textSize = arraygetDimensionPixelSize(0 / index /, -1 / default size /);
arrayrecycle();
注意,要记得调用 TypedArrayrecycle() 方法回收资源。
1、新建一个html文件,命名为testhtml。
2、在testhtml文件内,使用div标签创建一行文字,文字内容为“这是测试的文字内容”。
3、在testhtml文件内,设置div的id属性为abc,用于下面通过该id获得div对象。
4、在testhtml文件内,使用button标签创建一个按钮,按钮名称为“获取div里面的值”。
5、在testhtml文件中,给button按钮绑定onclick点击事件,当按钮被点击时,执行getdivc()函数。
6、在js标签中,创建getdivc()函数,在函数内,通过id(abc)获得div对象,使用text()方法获得div内的值,并使用alert()方法将值输出。
7、在浏览器中打开testhtml文件,点击按钮,查看结果。
Map<String,String> attr = new HashMap<String,String>();
attrput("name","张三");
String name = attrget("name");
Systemoutprintln(name);
使用 $("选择器")attr("属性名")
和 $("选择器")prop("属性名")
两者区别 是
对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。
Jquery获取select选中项 自定义属性的值的方法:
示例代码:
1、html代码:
<!DOCTYPE>
<html>
<head>
<meta >
#lili{font-weight:bold;color:red;}
</style>
</head>
<body>
<select id="mysel" title="选择提示">
<option>nba</option>
<option>fifa</option>
</select>
<script>
</script>
</body>
<html>
2、jquery代码获取自定义属性:
使用attr(name)获取title值:
<script>
alert($("#mysel")attr("title"));
</script>
3、显示结果:
以上就是关于如何在代码中获取attr属性的值全部的内容,包括:如何在代码中获取attr属性的值、jquery怎样获得所有div的id值,有多个div。用$("div").attr(id)只能获得一个div的id值、java中attr attrkey="name" attrvalue="张三" 怎么取出value的值等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)