我想创建一个自定义视图TestView
类,我可以通过new TestView()
. 然而,一个新的视图类需要一个 AttributeSet 对象。我从哪里得到那个 AttributeSet 以及它必须包括什么?
问问题
5774 次
2 回答
10
这不是强制性的,而且大多数时候你甚至不必担心它,只要你提供构造函数View
,将它们传递给super()
.
public CustomView(Context context) // No Attributes in this one.
{
super(context);
// Your code here
}
public CustomView(Context context, AttributeSet attrs)
{
super(context, attrs);
// Your code here
}
public CustomView(Context context, AttributeSet attrs, int default_style)
{
super(context, attrs, default_style);
// Your code here
}
View
android:*
负责处理您在将视图添加到布局时通常传入的所有属性的繁重工作。如果您定义了它们,您的构造函数可以使用这些属性或您自己的属性:
<com.blrfl.CustomView
android:id="@+id/customid"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
blrfl:foo="bar"
blrfl:quux="bletch"
/>
于 2010-12-16T14:53:32.937 回答
0
可以实现视图类提供的 3 个构造函数中的任何一个。因此,提供具有属性集的构造函数不是强制性的。
于 2010-12-20T08:51:47.060 回答