我正在构建自定义 View
包含两个标准 View 。我为每个包含的 View 都有一个默认样式,以及一个允许用户为每个包含的 View 指定自定义样式的自定义属性。我可以获得默认的 vs. 自定义样式,并将正确的样式 id 作为每个包含的 View 构造函数的第三个参数传递。我很难做的是生成 ViewGroup.LayoutParams
对于这些包含的 View ,基于 android:layout_height
和 android:layout_width
以适当的风格。
似乎我需要使用 ViewGroup.LayoutParams(Context, AttributeSet)
构造函数,以及 AttributeSet docs说我应该得到一个AttributeSet
通过
XmlPullParser parser = resources.getXml(myResouce);
AttributeSet attributes = Xml.asAttributeSet(parser);
... 但是会抛出一个 Resources$NotFoundException
来自 frameworks/base/libs/utils/ResourceTypes.cpp
的警告那Requesting resource %p failed because it is complex
.
因此,我的问题,按特异性降序排列:
- 有没有办法得到
XmlPullParser
与“复杂”元素一起使用? - 有没有其他方法可以得到
AttributeSet
对应于<style>
元素? - 有没有其他方法可以构造一个
LayoutParameters
那会注意layout_height
和layout_width
给定样式中的值?
最佳答案
static ViewGroup.LayoutParams layoutFromStyle(Context context,
int style) {
TypedArray t = context.getTheme().obtainStyledAttributes(
null,
new int[] { android.R.attr.layout_width,
android.R.attr.layout_height }, style, style);
try {
int w = t
.getLayoutDimension(0, ViewGroup.LayoutParams.WRAP_CONTENT);
int h = t
.getLayoutDimension(1, ViewGroup.LayoutParams.WRAP_CONTENT);
return new ViewGroup.LayoutParams(w, h);
} finally {
t.recycle();
}
}
关于android - 如何读取android :layout_height from style resource in custom View,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12378610/