Creating custom view

∥☆過路亽.° 提交于 2019-12-04 14:08:37

问题


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?


回答1:


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"
/>



回答2:


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



来源:https://stackoverflow.com/questions/4418700/creating-custom-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!