假设我有一个扩展 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/