android – 如何从styles.xml以编程方式检索样式属性
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了android – 如何从styles.xml以编程方式检索样式属性,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2115字,纯文字阅读大概需要4分钟。
内容图文
目前我正在使用WebView或TextView来显示来自我的某个应用程序中的Web服务的一些动态数据.
如果数据包含纯文本,则它使用TextView并从styles.xml应用样式.
如果数据包含HTML(主要是文本和图像),则使用WebView.
但是,这个WebView没有样式.因此它看起来与通常的TextView有很大的不同.
我已经读过,只需将一些HTML直接插入数据中,就可以在WebView中设置文本样式.这听起来很容易,但我想使用我的Styles.xml中的数据作为此HTML中所需的值,因此如果我更改样式,我将不需要更改两个位置上的颜色等等.
那么,我怎么能这样做呢?我做了一些广泛的搜索,但我发现无法从styles.xml中实际检索不同的样式属性.我在这里遗漏了什么或是否真的无法检索这些值?
我试图从中获取数据的样式如下:
<style name="font4">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textSize">14sp</item>
<item name="android:textColor">#E3691B</item>
<item name="android:paddingLeft">5dp</item>
<item name="android:paddingRight">10dp</item>
<item name="android:layout_marginTop">10dp</item>
<item name="android:textStyle">bold</item>
</style>
我主要对textSize和textColor感兴趣.
解决方法:
可以通过编程方式从styles.xml中检索自定义样式.
在styles.xml中定义一些任意样式:
<style name="MyCustomStyle">
<item name="android:textColor">#efefef</item>
<item name="android:background">#ffffff</item>
<item name="android:text">This is my text</item>
</style>
现在,检索这样的样式
// The attributes you want retrieved
int[] attrs = {android.R.attr.textColor, android.R.attr.background, android.R.attr.text};
// Parse MyCustomStyle, using Context.obtainStyledAttributes()
TypedArray ta = obtainStyledAttributes(R.style.MyCustomStyle, attrs);
// Fetch the text from your style like this.
String text = ta.getString(2);
// Fetching the colors defined in your style
int textColor = ta.getColor(0, Color.BLACK);
int backgroundColor = ta.getColor(1, Color.BLACK);
// Do some logging to see if we have retrieved correct values
Log.i("Retrieved text:", text);
Log.i("Retrieved textColor as hex:", Integer.toHexString(textColor));
Log.i("Retrieved background as hex:", Integer.toHexString(backgroundColor));
// OH, and don't forget to recycle the TypedArray
ta.recycle()
内容总结
以上是互联网集市为您收集整理的android – 如何从styles.xml以编程方式检索样式属性全部内容,希望文章能够帮你解决android – 如何从styles.xml以编程方式检索样式属性所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。