Creating custom view

前端 未结 2 1538
失恋的感觉
失恋的感觉 2021-02-10 20:41

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. F

2条回答
  •  误落风尘
    2021-02-10 21:18

    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:

    
    

提交回复
热议问题