【问题标题】:how to get AttributeSet properties如何获取 AttributeSet 属性
【发布时间】:2011-11-07 13:27:32
【问题描述】:

假设我有一个扩展 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 检索构造函数中的属性?假设背景字段中的可绘制对象。

public MapView(Context context, AttributeSet attrs) {
}

【问题讨论】:

    标签: android android-layout attributes


    【解决方案1】:

    在一般情况下,您会这样做:

    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 中元素的索引如何影响。但是,在您的特定情况下,使用 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();
    }
    

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

    【讨论】:

    • attrsArray的顺序我们应该知道什么?
    • getDimensionPixelSize 抛出异常,使用 getLayoutDimension 工作正常
    • 我还看到在一些地方使用R.styleable.Whatever 代替硬编码数组(然后使用R.styleable.Whatever_blah 来获取blah 属性,而不是硬编码索引);你可以在这个答案中添加这种方法吗?
    猜你喜欢
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-22
    • 2011-11-06
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多