我有一个庞大的Android代码库,并且正在编写一个自定义lint规则,以检查某些属性的值是否落在给定范围内。
例如,我有这个组件:
<MyCustomComponent
my:animation_factor="0.7"
...>
</MyCustomComponent>
我希望编写一个lint规则,警告开发人员谨慎使用my:animation_factor
的值>=1。
我按照http://tools.android.com/tips/lint-custom-rules上的说明操作,并使用以下代码成功地检索了my:animation_factor
的值:
import com.android.tools.lint.detector.api.*;
public class XmlInterpolatorFactorTooHighDetector {
....
@Override
public Collection<String> getApplicableElements() {
return ImmutableList.of("MyCustomComponent");
}
@Override
public void visitElement(XmlContext context, Element element) {
String factor = element.getAttribute("my:animation_factor");
...
if (value.startsWith("@dimen/")) {
// How do I resolve @dimen/xyz to 1.85?
} else {
String value = Float.parseFloat(factor);
}
}
}
当属性(例如 my:animation_factor
)具有字面值(例如 0.7
)时,此代码可以正常工作。
但是,当属性值为资源(例如 @dimen/standard_anim_factor
)时,element.getAttribute(...)
返回的是属性的字符串值而不是实际解析后的值。
例如,当我有一个像这样的 MyCustomComponent
:
<MyCustomComponent
my:animation_factor="@dimen/standard_anim_factory"
...>
</MyCustomComponent>
并且 @dimen/standard_anim_factor
在其他地方有定义:
<dimen name="standard_anim_factor">1.85</dimen>
然后字符串factor
会变成"@dimen/standard_anim_factor"而不是"1.85"。
在处理MyCustomComponent
元素时,有没有一种方法来解析"@dimen/standard_anim_factor"为实际的资源值(即"1.85")?
0.7
,那么它怎么会指向standard_anim_factor
?或者如果它指向它,那么问题是什么? - Murtaza Khursheed Hussain