android – 从父级的样式定义中获取子级的样式属性

前端之家收集整理的这篇文章主要介绍了android – 从父级的样式定义中获取子级的样式属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
问题标题可能是荒谬的.我正在创建一组自定义视图,这些视图将放置在单个父布局中 – 自定义FrameLayout.

这些自定义视图具有自己的样式attr,它们使用父级样式attr设置.

例如,将Parent视为自定义FrameLayout.它的样式attr在attrs.xml中定义:

<attr name="parentStyleAttr" format="reference" />

孩子也有它的attr:

<attr name="childStyleAttr" format="reference" />

并且Parent将其可定制的attr定义为:

<declare-styleable name="Parent">
    <attr name="childStyleAttr" />
</declare-styleable>

孩子的风格attr:

<declare-styleable name="Child">
    <attr name="childBgColor" format="color" />
</declare-styleable>

在此之后,我为父母定义了一种风格:

<style name="ParentStyle">
    <item name="childStyleAttr">@style/ChildStyle</item>
</style>

和一个儿童:

<style name="ChildStyle">
    <item name="childBgColor">@color/blah</item>
</style>

对于Parent,我在app的主题中设置了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中设置的style属性的值.

这不起作用:

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);

    ....
}

我不相信这是否是正确的做法.有人可以帮助解决这个问题吗?

解决方法

我会选择扩展布局并创建自定义布局的简单解决方案,将其属性发送给它的子项 while adding them
原文链接:https://www.f2er.com/android/317724.html

猜你在找的Android相关文章