Search code examples
androidviewcustom-viewviewgroup

Ondraw method not calling in custom view


I am making custom view using custom ViewGroup and custom View in Android.

public class Custom_ViewGroup extends ViewGroup
{
public Custom_ViewGroup(Context context)
{
    super(context);
    addView(new OwnView(context));
}

public Custom_ViewGroup(Context context,AttributeSet attrs) 
{
    super(context, attrs);
    addView(new OwnView(context));
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
    // TODO Auto-generated method stub
}

class OwnView extends View
{
    public OwnView(Context context)
    {
        super(context);
        System.out.println("on constructor");
    }
    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);

        System.out.println("ondraw child");
    }
  }
}

onDraw() method of OwnView class is not calling. constructor of OwnView class called. I have used invalidate() method after adding view, but it did not work.


Solution

  • This is your problem

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b)
    {
        // TODO Auto-generated method stub
    }
    

    Your view is never laid-out, so it will not draw. You need to implement the onLayout method properly. Also, if your ViewGroup contains only a single view, consider using FrameLayout instead of ViewGroup.