如何从styles.xml以编程方式检索样式属性

目前,我正在使用WebView或TextView来显示一些来自我的应用程序中的web服务的dynamic数据。 如果数据包含纯文本,则使用TextView并应用styles.xml中的样式。 如果数据包含HTML(主要是文本和图像),则使用WebView。

但是,这个WebView是无风格的。 因此,它看起来与通常的TextView有很大的不同。 我读过,可以通过简单地将一些HTML直接插入到数据中来在WebView中设置文本的样式。 这听起来很容易,但我想使用Styles.xml中的数据作为这个HTML所需的值,所以如果我改变了我的样式,我不需要改变两个位置的颜色等等。

那么,我将如何能够做到这一点? 我已经做了一些广泛的search,但是我没有find从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() 

@Ole给出的答案似乎在使用某些属性时会中断,如shadowColor,shadowDx,shadowDy,shadowRadius(这些只是我发现的几个,可能还有更多)

我不知道为什么会出现这个问题,这是我在这里问的,但@AntoineMarques编码风格似乎解决了这个问题。

为了使这个工作的任何属性,它会是这样的


首先,定义一个样式来包含像这样的资源id

attrs.xml

 <resources> <declare-styleable name="MyStyle" > <attr name="android:textColor" /> <attr name="android:background" /> <attr name="android:text" /> </declare-styleable> </resources> 

然后在代码中,你会这样做的文本。

 TypedArray ta = obtainStyledAttributes(R.style.MyCustomStyle, R.styleable.MyStyle); String text = ta.getString(R.styleable.MyStyle_android_text); 

使用这种方法的好处是,你正在检索价值的名称,而不是索引。

如果接受的解决scheme不工作尝试将attr.xml重命名为attrs.xml(为我工作)