Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a class A that extends class View.

I have a class B that extends class A.

Now I'm trying to add class B into my xml however I'm unable to do that whereas I'm able to add class A into my xml.

One more thing which I've noticed is that all other custom classes which directly extends View are visible inside my xml.

I wanna know whether is there any way of adding a class which extends another class which in turn extends View into my xml?

NOTE : I'm using proper xml format and complete package name.

CLASS A

public class A extends View implements Serializable{

    public A(final Context context, final AttributeSet attrs,
            final int defStyle, final SomeEnum myType) {
        super(context, attrs, defStyle);
    }

    public A(final Context context, final AttributeSet attrs,
            final SomeEnum myType) {
        this(context, attrs, 0, testStateType);
    }

    public A(final Context context,
            final SomeEnum myType) {
        this(context, null, 0, testStateType);
    }

    public A(final Context context,
            final AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onSizeChanged(final int w, final int h, final int oldw,
            final int oldh) {
        invalidate();
    }

    @Override
    protected void onMeasure(final int widthMeasureSpec,
            final int heightMeasureSpec) {
    }

    @Override
    protected void onDraw(Canvas canvas) {

    }
}

CLASS B

public class B extends A
{
    public B(final Context context,
            final AttributeSet attrs, final int defStyle, final SomeEnum myType)
    {
        super(context, attrs, defStyle, testStateType);
    }

    public B(final Context context, final AttributeSet attrs, final SomeEnum myType)
    {
        this(context, attrs, 0, testStateType);
    }

    public B(final Context context, final SomeEnum myType)
    {
        this(context, null, 0, testStateType);
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
179 views
Welcome To Ask or Share your Answers For Others

1 Answer

class B is missing the constructor with the default arguments. Add:

public B(final Context context, final AttributeSet attrs) {
    super(context, attrs);
}

to your class and you will be able to inflate it from an XML with your other views.

In general, adding custom parameters to a View's constructors is not a good practice. Use a custom attribute for that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...