这个问题的标题可能有点无意义。我正在创建一些自定义视图,它们将被放置在一个单独的父布局中 - 一个自定义的FrameLayout
。
这些自定义视图有它们自己的样式属性,这些属性使用父布局的样式属性进行设置。
以Parent
为例,它是自定义的FrameLayout
。它的样式attr
在attrs.xml
中定义:
<attr name="parentStyleAttr" format="reference" />
Child
也有它自己的属性:
<attr name="childStyleAttr" format="reference" />
而 Parent
则定义了它的可定义样式属性为:
<declare-styleable name="Parent">
<attr name="childStyleAttr" />
</declare-styleable>
Child's
可定义的属性:
<declare-styleable name="Child">
<attr name="childBgColor" format="color" />
</declare-styleable>
接下来,我为父元素定义一个样式:
<style name="ParentStyle">
<item name="childStyleAttr">@style/ChildStyle</item>
</style>
还有一个用于 Child
的:
<style name="ChildStyle">
<item name="childBgColor">@color/blah</item>
</style>
对于Parent
,我在应用程序的主题中设置了parentStyleAttr
:
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="parentStyleAttr">@style/ParentStyle</item>
</style>
现在,当创建
Parent
时,它会填充包含Child
的布局:LayoutInflater.from(getContext()).inflate(R.layout.child, this, true);
在初始化Child
时,我需要读取@style/ChildStyle
中设置的样式属性值-childBgColor
。
以下方法不可行:
final TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.Child, R.attr.childStyleAttr, R.style.ChildStyle);
我目前读取 attr/childBgColor
的方式是:
public Child(Context context, AttributeSet attrs, int defStyleAttr) {
super(createThemeWrapper(context), attrs, defStyleAttr);
initialize(attrs, defStyleAttr, R.style.ChildStyle);
}
private static ContextThemeWrapper createThemeWrapper(Context context) {
final TypedArray forParent = context.obtainStyledAttributes(
new int[]{ R.attr.parentStyleAttr });
int parentStyle = forParent.getResourceId(0, R.style.ParentStyle);
forParent.recycle();
TypedArray forChild = context.obtainStyledAttributes(parentStyle,
new int[]{ R.attr.childStyleAttr });
int childStyleId = forChild.getResourceId(0, R.style.ChildStyle);
forChild.recycle();
return new ContextThemeWrapper(context, childStyleId);
}
void initialize(AttributeSet attrs, int defStyleAttr, int defStyleRes) {
Context context = getContext();
final Resources res = getResources();
final TypedArray a = context.obtainStyledAttributes(R.styleable.Child);
....
}
我不确定这是否是正确的方法。有人能帮助澄清一下吗?
appcompat
更新中实现的父主题继承:https://chris.banes.me/2015/04/22/support-libraries-v22-1-0/#androidtheme 作者提到了LayoutInflater.Factory2
作为启用父主题继承的类。 - hidro在子元素中读取xml属性是否更简单...
这就是我想做的。为了使事情更清晰,我可以在AppTheme
下初始化childStyleAttr
并很好地读取childBgColor
。但如果我选择这样做,我将不得不为AppTheme
下的 所有 子项初始化样式属性。相反,我希望设置parentStyleAttr
,它应该处理所有子项的样式属性。 - Vikram