创建自定义视图

Chr*_*ian 3 android android-ui

我想创建一个自定义视图TestView类,我可以通过它创建对象new TestView().但是,新的视图类需要AttributeSet对象.从哪里获取AttributeSet以及它包含哪些内容?

Blr*_*rfl 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
}
Run Code Online (Sandbox Code Playgroud)

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"
/>
Run Code Online (Sandbox Code Playgroud)