2012-09-11 36 views
1

我正在構建包含兩個標準視圖的自定義View。我對每個包含的View都有一個默認樣式,並且有一個自定義屬性,可以讓用戶爲每個包含的View指定一個自定義樣式。我可以得到默認的自定義樣式很好,並傳遞正確的樣式ID作爲每個包含View的構造函數的第三個參數。我正在很難做的是根據android:layout_heightandroid:layout_width以適當的風格生成ViewGroup.LayoutParams這些包含Views。如何從樣式資源中自定義查看android:layout_height查看

似乎像我需要使用ViewGroup.LayoutParams(Context, AttributeSet)構造函數和AttributeSet docs說我應該得到一個通過AttributeSet

XmlPullParser parser = resources.getXml(myResouce); 
AttributeSet attributes = Xml.asAttributeSet(parser); 

...但是,拋出一個Resources$NotFoundExceptionframeworks/base/libs/utils/ResourceTypes.cpp警告那Requesting resource %p failed because it is complex

因此,我的問題,在降低特異性的順序:

  1. 有沒有辦法得到一個XmlPullParser以「複雜」的元素的作品?
  2. 有沒有其他方法可以得到AttributeSet對應於<style>元素?
  3. 有沒有其他的方法來構造一個LayoutParameters會注意給定風格的layout_heightlayout_width值?

回答

2
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(); 
     } 
    }