4

I want to create a custom view TestView class for which I can create object via new TestView(). A new view class however needs a AttributeSet object. From where do I get that AttributeSet and what does it have to include?

Christian
  • 25,249
  • 40
  • 134
  • 225

2 Answers2

10

It's not mandatory, and most times you don't even have to worry about it as long as you provide constructors from View that pass them along to 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 takes care of doing the heavy lifting for dealing with all of the android:* attributes that you'd usually pass in when adding the view to a layout. Your constructors could make use of those attributes or your own if you've defined them:

<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"
/>
Blrfl
  • 6,817
  • 1
  • 25
  • 25
  • I spent many hours trying to generate an attrs set on the fly, i found it near on impossible to find any documentation or examples on how to do this. A good question might be how to set the foo and quux properties when not using attrs, and using new CustomView(). – Emile Dec 20 '10 at 14:39
  • CustomView(String foo, String bletch) perhaps. – Emile Dec 20 '10 at 14:40
  • Ask it and I'll post an answer. – Blrfl Dec 20 '10 at 15:21
  • Questioned asked here, let me know if its an appropriate question. http://stackoverflow.com/questions/4495511/android-how-to-pass-custom-component-parameters-in-java-and-xml – Emile Dec 21 '10 at 01:07
0

Either of 3 constructor provided by view class can be implemented.. so providing constructor with attributeset is not mandatory.

Zoombie
  • 3,590
  • 5
  • 33
  • 40