如何获取AttributeSet属性

时间:2011-11-07 13:27:32

标签: android android-layout attributes

假设我有一个扩展ViewGroup的类

public class MapView extends ViewGroup

它包含在布局map_controls.xml中,如此

<com.xxx.map.MapView
    android:id="@+id/map"
    android:background="@drawable/address"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
</com.xxx.map.MapView>

如何从AttributeSet中检索构造函数中的属性?让我们说一下背景场中的drawable。

public MapView(Context context, AttributeSet attrs) {
}

1 个答案:

答案 0 :(得分:60)

在一般情况下,你喜欢这样:

public MapView(Context context, AttributeSet attrs) {
    // ...

    int[] attrsArray = new int[] {
        android.R.attr.id, // 0
        android.R.attr.background, // 1
        android.R.attr.layout_width, // 2
        android.R.attr.layout_height // 3
    };
    TypedArray ta = context.obtainStyledAttributes(attrs, attrsArray);
    int id = ta.getResourceId(0 /* index of attribute in attrsArray */, View.NO_ID);
    Drawable background = ta.getDrawable(1);
    int layout_width = ta. getLayoutDimension(2, ViewGroup.LayoutParams.MATCH_PARENT);
    int layout_height = ta. getLayoutDimension(3, ViewGroup.LayoutParams.MATCH_PARENT);
    ta.recycle();
}

注意 attrsArray 中元素的索引是如何重要的。但是,在您的特定情况下,它与使用吸气剂一样好,就像您自己发现的那样:

public MapView(Context context, AttributeSet attrs) {
    super(context, attrs); // After this, use normal getters

    int id = this.getId();
    Drawable background = this.getBackground();
    ViewGroup.LayoutParams layoutParams = this.getLayoutParams();
}

这是有效的,因为您在com.xxx.map.MapView上拥有的属性  是View基类在其构造函数中解析的基本属性。如果您想定义自己的属性,请查看此问题和优秀答案:Declaring a custom android UI element using XML

相关问题