Kevin Mueller
Kevin Mueller

Reputation: 668

Add View To View Without XML

I have this class that extends View (it's in C# because I use Xamarin)

public class ScannerOverlay : View
{

    public ScannerOverlay(Context context) : base(context)
    {
       //Initializing some values here
    }

    protected override void OnDraw(Canvas canvas)
    {
        base.OnDraw(canvas);

        //Draw some stuff on the canvas
    }
}

I create this view using: View v = new ScannerOverlay(context);

Now I want to add a button to this view. How do I do this? The view has no layout whatsoever so AddView() is not going to work. And from what I found it's not possible to draw a button on a canvas.

Upvotes: 3

Views: 373

Answers (3)

Vishal Pawar
Vishal Pawar

Reputation: 4340

ViewGroup extends View so you directly get all features of View event though you extend ViewGroup. In this way you can add new View to CustomView directly.

public class ScannerOverlay : ViewGroup
{

    public ScannerOverlay(Context context) : base(context)
    {
       //Initializing some values here
    }

    protected override void OnDraw(Canvas canvas)
    {
        base.OnDraw(canvas);

        //Draw some stuff on the canvas
    }
}

Upvotes: 0

HendraWD
HendraWD

Reputation: 3043

Basically, you can't add a View to another View.

Hard Way: You can create a View as if it has many Views inside it, but you should draw them manually using Canvas and Paint, also handle the click based on touch location of that each "fake" View. So it will take you a lot of time. This is called Custom View.

Easy Way: You can add any View to a ViewGroup and any child of ViewGroup like FrameLayout, LinearLayout, and RelativeLayout with ViewGroup.AddView(view) function. This is called Compound View.

Upvotes: 1

Kevin Mueller
Kevin Mueller

Reputation: 668

Fixed it by extending from RelativeLayout instead of View.

If (like in my case) the OnDraw Method is not getting called, set the following in the constructor: this.SetWillNotDraw(false);

Upvotes: 1

Related Questions