在较旧的平台上阅读较新的主题属性

Jak*_*ton 30 android android-theme

我试图从主题和样式中读取属性值,这些属性值是为比运行我的应用程序更新的平台而设计的.

请不要问为什么.如果您对我编写的库有所了解,那么您应该已经知道我喜欢推动平台的功能:)

我的假设是,在编译Android样式时,属性常量是用于键的因素,因此理论上应该能够以某种方式在任何平台上读取.这就是我观察到在我的其他库中使用布局XML而没有遇到任何问题.

这是一个显示问题的基本测试用例.这应该使用Android 3.0+编译.

<resources>
    <style name="Theme.BreakMe">
        <item name="android:actionBarStyle">@style/Widget.BreakMe</item>
    </style>
    <style name="Widget.BreakMe" parent="android:Widget">
        <item name="android:padding">20dp</item>
    </style>
</resources>
Run Code Online (Sandbox Code Playgroud)

android:actionBarStyle具体使用这一事实是无关紧要的.应该理解的是,它的属性仅从Android 3.0开始才可用.

以下是我在Android 3.0之前的平台上尝试访问这些值的方法.

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Break Me"
    style="?android:attr/actionBarStyle"
    />
Run Code Online (Sandbox Code Playgroud)

<declare-styleable name="Whatever">
    <item name="datStyle" format="reference" />
</declare-styleable>

<style name="Theme.BreakMe.Take2">
    <item name="datStyle">?android:attr/actionBarSize</item>
</style>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Break Me"
    style="?attr/datStyle"
    />
Run Code Online (Sandbox Code Playgroud)

TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.actionBarStyle, outValue, true);
Run Code Online (Sandbox Code Playgroud)

int[] Theme = new int[] { android.R.attr.actionBarSize };
int Theme_actionBarSize = 0;
TypedArray a = context.obtainStyledAttributes(attrs, Theme);
int ref = a.getResourceId(Theme_actionBarSize, 0);
Run Code Online (Sandbox Code Playgroud)

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ActionBar, android.R.attr.actionBarStyle, 0);
Run Code Online (Sandbox Code Playgroud)

所有这些都导致LogCat中出现此错误:

E/ResourceType(5618): Style contains key with bad entry: 0x010102ce
Run Code Online (Sandbox Code Playgroud)

0x010102ce常数是属性值的android.R.attr.actionBarStyle,这似乎表明该平台拒绝属性之前,我甚至可以得到一个机会来访问它的价值.

我正在寻找任何其他方式来从主题中读取这样的属性.我很相信,一旦我获得了样式参考,我就不会有阅读其属性的麻烦.

有没有办法做到这一点?

Com*_*are 15

我的假设是,在编译Android样式时,属性常量是用于键的因素,因此理论上应该能够以某种方式在任何平台上读取.

可能,虽然这不是我解释C++源代码的方式,但却引发了你所看到的错误.看看ResTable::Theme::applyStyle()frameworks/base/libs/utils/ResourceTypes.cpp.

我的解释是,Android具有相当于package-> types->可能条目的内存表:

numEntries = curPI->types[t].numEntries;
Run Code Online (Sandbox Code Playgroud)

您的条目索引高于已知最高条目:

if (e >= numEntries) {
    LOGE("Style contains key with bad entry: 0x%08x\n", attrRes);
    bag++;
    continue;
}
Run Code Online (Sandbox Code Playgroud)

它们可能android与其他软件包处理不同- android在固件构建时使用已知值(并且您生成的条目索引更高,因为它来自较新的平台),非android假设任何有效的.

如果我的猜测是正确的,那么你想要做的就行不通.话虽这么说,我的C++时代在我的后视镜中非常严重,所以我可能会误解我所看到的.