【问题标题】:Ondraw method not calling in custom viewOndraw 方法未在自定义视图中调用
【发布时间】:2023-04-02 05:24:01
【问题描述】:

我正在使用 Android 中的自定义 ViewGroup 和自定义 View 制作自定义视图。

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");
    }
  }
}

OwnView 类的 onDraw() 方法没有被调用。调用了OwnView 类的构造函数。我在添加视图后使用了 invalidate() 方法,但它不起作用。

【问题讨论】:

    标签: android view custom-view viewgroup


    【解决方案1】:

    这是你的问题

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

    您的视图从不布局,因此不会绘制。您需要正确实现onLayout 方法。此外,如果您的ViewGroup 仅包含一个视图,请考虑使用FrameLayout 而不是ViewGroup

    【讨论】:

    • “另外,如果您的ViewGroup 只是一个视图”,您的意思是它是否只有一个子视图?
    • 所以如果它只有一个子视图,最好只删除“一个孩子”的父母
    • @pskink 可能。这取决于子视图的布局方式。
    • @pathfinderelite 谢谢,它正在工作。但我不明白你使用 FrameLayout 的观点。你能多介绍一下 FrameLayout 的使用吗....
    • @Akashsingla19 我并不是说你应该使用FrameLayout。我是说如果您的 ViewGroup 仅包含一个孩子,您可能想要使用它。你可以阅读更多here
    猜你喜欢
    • 2015-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多