android - 如何获取 AttributeSet 属性

标签 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 检索构造函数中的属性?假设背景字段中的可绘制对象。

public MapView(Context context, AttributeSet attrs) {
}

最佳答案

一般情况下,你会这样做:

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

关于android - 如何获取 AttributeSet 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8037101/

相关文章:

java - 如何检查所有textview文本在scrollview中是否可见

android 模拟器不在 iMac 中的蓝牙耳机上播放声音

android - 无法创建 flutter 项目 : No option specified for the output directory error

java - Android 自定义 View 中的数据绑定(bind)

python - 如何在Python中的语料库上使用 "collocation_list"函数?

c - __attribute__ 优化,指定多个标志,以及不同 -O 级别的失败代码

java - Dagger 2 Activity 注入(inject)不起作用

xml 中的 Android 谷歌地图 fragment 。我得到 "Unexpected namespace prefix"

java - Android Studio 中的多个根标签

jQuery、SVG : How to animate an attribute value (not style property)?