首页 > 解决方案 > 如何从本机视图获取属性

问题描述

如何从“本机视图”取回属性?

我展开AppBarLayout并在我的 XML 布局中使用了以下属性:

app:expanded="false"

我知道如何从自定义样式中获取属性,但是如何从标准属性中获取它?

TypedArray ta = context.obtainStyledAttributes(attrs, ???? );
expanded = ta.getBoolean( ???? , false);

谢谢你的帮助。

标签: javaandroidlayoutattr

解决方案


我找到了一种方法,但我不确定这是一个好方法。

我定义了一个样式并重新定义了相同的名称:

<declare-styleable name="attrs_global_boolean">
    <attr name="expanded" format="boolean"/>
    ....
</declare-styleable>

<declare-styleable name="AppBarLayout"> // here i use the same name of the original class, doesn't seem to give me any error, maybe it is better do use AppBarLayoutCustom or AppBarLayoutExtra (or any other name ?? )
    <attr name="expanded"/>
</declare-styleable>

接着

final static protected int[] STYLEABLE_AppBarLayout = R.styleable.AppBarLayout;
TypedArray ta = context.obtainStyledAttributes(attrs, STYLEABLE_AppBarLayout );
expanded = ta.getBoolean( R.styleable.AppBarLayout_expanded, false);
ta.recycle();

有没有办法在不需要重新定义具有相同属性名称的样式的情况下获得它?有更好的方法吗?

谢谢


推荐阅读