如何获取AttributeSet属性

Ray*_*non 21 android attributes android-layout

假设我有一个扩展ViewGroup的类

public class MapView extends ViewGroup
Run Code Online (Sandbox Code Playgroud)

它包括在布局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>
Run Code Online (Sandbox Code Playgroud)

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

public MapView(Context context, AttributeSet attrs) {
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*lts 62

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

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();
}
Run Code Online (Sandbox Code Playgroud)

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

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();
}
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为您拥有的com.xxx.map.MapView 属性是View基类在其构造函数中解析的基本属性.如果你想定义自己的属性,看看这个问题和优秀答案:使用XML声明自定义android UI元素

  • getDimensionPixelSize抛出异常,使用getLayoutDimension工作正常 (2认同)