Android从CustomView绘制文本视图

Android从CustomView绘制文本视图,android,view,android-canvas,draw,Android,View,Android Canvas,Draw,我有一个像这样的自定义视图: public class CustomView extends View { protected Context c; protected String text; ... // and some more useful member variables... public CustomView(String text, Context c, ...) { this.text = text; this.c =

我有一个像这样的自定义视图:

public class CustomView extends View {

    protected Context c;
    protected String text;
    ... // and some more useful member variables...

    public CustomView(String text, Context c, ...) {

         this.text = text; this.c = c;
         ...
    }

    @Override
    protected void onDraw(Canvas canvas) {

        super.onDraw(canvas);

        LinearLayout ll = new LinearLayout(c);
        TextView tv = new TextView(c);
        tv.setText(text);
        ll.addView(tv);

        ll.draw(canvas);
    }
在我的主要活动中,我会这样做:

    RelativeLayout gamelayout = (RelativeLayout) findViewById(R.id.gamelayout);

    CustomView customview = new CustomView("Textview text", this);
    gamelayout.addView(customview);

我的问题是,没有绘制任何内容,绘制的文本视图不会出现在“游戏布局”中。我做错了什么?

TextView对象无法直接绘制到画布,因为您已经这样做了,您需要指定一个布局,然后执行以下操作:

ll.layout(0, 0, canvas.getWidth(), canvas.getHeight()); //Modify values as needed
就个人而言,我很惊讶调用
ll.draw()
时没有抛出错误。除非您需要绘制文本视图,否则我更喜欢在画布上绘制文本:

canvas.drawText(...)

您的
线性布局未附加到视图中


尝试
this.addView(ll)
将线性布局添加到视图中。

您没有将文本视图附加到屏幕上实际显示的任何父视图!我不知道你想在这里做什么这就是我想通过gamelayout.addView(customview)来做的。至少据我所知,这将调用自定义视图的onDraw方法。游戏布局显示在屏幕上。您可以尝试此操作。addView(ll)。。。在调用ll.draw(画布)之前将ll附加到gameLayout;不幸的是,在添加这一行之后,仍然没有绘制任何内容:(.canvas.getWidth()返回的确切内容是什么?还有其他建议吗?canvas.getWidth()应返回正在使用的绘图画布的宽度。如果调试并检查值,则应获得大于0的内容,您不能添加
视图组
,例如
线性布局
。为此,您需要
视图组