我想创建一个自定义 View TestView
类,我可以通过 new TestView()
为其创建对象。
然而,一个新的 View 类需要一个 AttributeSet 对象。我从哪里获得该 AttributeSet 以及它必须包含什么?
最佳答案
这不是强制性的,大多数时候你甚至不必担心它,只要你从 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
负责处理您在将 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"
/>
关于android - 创建自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4418700/