android - 如何读取android :layout_height from style resource in custom View

标签 android android-custom-view

我正在构建自定义 View包含两个标准 View 。我为每个包含的 View 都有一个默认样式,以及一个允许用户为每个包含的 View 指定自定义样式的自定义属性。我可以获得默认的 vs. 自定义样式,并将正确的样式 id 作为每个包含的 View 构造函数的第三个参数传递。我很难做的是生成 ViewGroup.LayoutParams对于这些包含的 View ,基于 android:layout_heightandroid: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 .

因此,我的问题,按特异性降序排列:

  1. 有没有办法得到 XmlPullParser与“复杂”元素一起使用?
  2. 有没有其他方法可以得到 AttributeSet对应于 <style>元素?
  3. 有没有其他方法可以构造一个 LayoutParameters那会注意layout_heightlayout_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/

相关文章:

android - 如何在 onMeasue 中处理自定义 View 的权重?

java - 为什么final变量没有内部类就返回?

安卓计费;如何解决 "The item you were attempting to purchase could not be found"

java - 按标签搜索 FlickR 照片

java - GraphView 中的虚线

android - 获取自定义Listview Android中的总行数

android - btn.performClick() 无法模拟对象,但 Activity 可以调用该函数

android - Android中应用程序包名称中的应用程序名称和应用程序图标

android - 如何在属性集中获取对另一个 View 的引用 - 类似于相对布局中的 layout_below = "id"?

android - 如何动画渐变?