我确信我需要的东西有一个正确的答案,但我找不到:(
我需要以编程方式从主题的样式中读取属性。。。这里有一些简单的代码,让它更容易理解。
//Custom attributes
<declare-styleable name="Style_lib">
<attr name="layoutElementStyle" format="reference"/>
</declare-styleable>
<declare-styleable name="AppTheme">
<attr name="customTheme" format="reference"/>
</declare-styleable>
<declare-styleable name="CustomView">
<attr name="customAttribute" format="reference"/>
</declare-styleable>
// Theme / style
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
<item name="customTheme">@style/CustomTheme</item>
</style>
<style name="CustomTheme" >
<item name="layoutElementStyle">@style/StyleElement_CustomTheme</item>
</style>
<style name="StyleElement_CustomTheme" >
<item name="customAttribute">@color/Red</item>
</style>
// Layout
<FrameLayout
...
android:theme="?attr/customTheme">
<CustomElementView
...
style="?attr/layoutElementStyle" />
...
//// Here everything works as expected, I don't have any probleme to apply theme or style, my problem is i need to get style="?attr/layoutElementStyle" programmatically in my custom view.
/// CustomView
private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes){
int style = attrs.getStyleAttribute();
And now ??? how can I get my attribute from the style provided by my theme ? style is the same value of R.attr.layoutElementStyle. But how can I obtain customAttribute inside StyleElement_CustomTheme provided by CustomTheme apply in customTheme of AppTheme...
}
我知道在没有样式或主题的情况下如何读取自定义属性。所以,请理解我的问题是如何从主题提供的自定义样式中读取自定义属性:(这个exmaple已经收缩了。当然,仅仅是用颜色阅读是没有意义的:(。
谢谢大家。
测试它的
int idStyle = getResources().getIdentifier("CustomTheme", "style", getPackageName());
好的,我刚刚成功。
when you obtain the value of your style attribute, it give you in this case the value of ?attr/layoutElementStyle. But since this is itself a style, the correct way to do it is:
int style = attrs.getStyleAttribute();
TypedArray a = context.obtainStyledAttributes(style, R.styleable.Style_lib);
int elementStyleId = a.getResourceId(R.styleable.Style_lib_layoutElementStyle, -1);
a.recycle();
and then just do it as usual way;
context.obtainStyledAttributes(elementStyleId , R.stylable.CustomView);
and so.
因此,对于样式属性,您只需要首先检索当前样式,然后访问该属性。
如果有人是另一种体验,我很感激对此的一些感觉。
谢谢。