我希望从样式资源中提取多个属性(仅关心TextAppearance组中的属性)
以下是定义样式的代码:
以下是定义样式的代码:
<style name="Label" parent="@android:style/TextAppearance.Small">
<item name="android:textColor">@color/floatlabel_text</item>
<item name="android:textSize">8dp</item>
<item name="android:textStyle">bold</item>
</style>
首次尝试
首先,我尝试了TextView(代码行663-731)的实现方式,但后来发现我们无法访问com.android.internal.R
部分解决方案
这就是为什么我转而使用了这个解决方案:https://dev59.com/omsz5IYBdhLWcg3wcXXF#7913610
所以,我创建了textAppearanceAttr来替换com.android.internal.R.styleable.TextAppearance(只包含我感兴趣的10/13个TextAppearance属性)
int[] textAppearanceAttr = new int[]{
android.R.attr.textColor,
android.R.attr.textSize,
android.R.attr.typeface,
android.R.attr.fontFamily,
android.R.attr.textStyle,
android.R.attr.textAllCaps,
android.R.attr.shadowColor,
android.R.attr.shadowDx,
android.R.attr.shadowDy,
android.R.attr.shadowRadius};
以下是我使用它的方法。我获取样式资源ID(资源由clTextAppearance属性引用)。
int ap = a.getResourceId(R.styleable.CustomLabelLayout_clTextAppearance, android.R.style.TextAppearance_Small);
TypedArray appearance = mContext.obtainStyledAttributes(ap, textAppearanceAttr);
以下是我如何获取属性(仍然遵循上面链接中的答案):
mLabelTextColor = appearance.getColorStateList(0);
mLabelTextSize = appearance.getDimensionPixelSize(1, 15);
mLabelTypeface = appearance.getInt(2, -1);
mLabelFontFamily = appearance.getString(3);
mLabelTextStyle = appearance.getInt(4, -1);
(5 more...)
当前问题
看起来只有第一个属性被设置了,其他的要么使用默认值,要么为空。
似乎可行的一个技巧
单独的数组:
int[] textSizeAttr = new int[] { android.R.attr.textSize};
int[] textStyleAttr = new int[] { android.R.attr.textStyle};
然后像这样获取属性
appearance.recycle();
appearance = mContext.obtainStyledAttributes(ap, textSizeAttr);
mLabelTextSize = appearance.getDimensionPixelSize(0, 15);
appearance.recycle();
appearance = mContext.obtainStyledAttributes(ap, textStyleAttr);
mLabelTextStyle = appearance.getInt(0, -1);
appearance.recycle();
现在做这件事情是浪费时间。
问题
- 我想知道为什么一次性获取所有属性不起作用。
- 是否有解决方案(不需要额外的工作)?
编辑1
我在这里找到了类似的内容:https://dev59.com/MGYr5IYBdhLWcg3wYZSD#13952929,不知何故它可以工作。 直到我将更多属性添加到数组中,然后一切都变得混乱无序。
例如:
int[] attrs = {android.R.attr.textColor,
android.R.attr.textSize,
android.R.attr.background,
android.R.attr.textStyle,
android.R.attr.textAppearance,
android.R.attr.textColorLink,
android.R.attr.orientation,
android.R.attr.text};
如果我使用上面的数组获取文本,它就能工作。
String text = ta.getString(7);
但如果我将数组更改为以下内容,则会失败(将 android.R.attr.orientation 替换为 android.R.attr.shadowColor)
int[] attrs = {android.R.attr.textColor,
android.R.attr.textSize,
android.R.attr.background,
android.R.attr.textStyle,
android.R.attr.textAppearance,
android.R.attr.textColorLink,
android.R.attr.shadowColor,
android.R.attr.text};
为什么会发生这种情况?(问题 #1)
a.getResourceId(R.styleable.CustomLabelLayout_clTextAppearance, android.R.style.TextAppearance_Small)
返回了你的Label
样式 id(这是我理解你想要的)吗? - Antoine MarquesmContext.obtainStyledAttributes(R.style.Label, textAppearanceAttr)
。 - Antoine Marques