【问题标题】:Android draw TextView from CustomViewAndroid 从 CustomView 绘制 TextView
【发布时间】:2013-01-23 20:14:26
【问题描述】:

我有一个如下所示的自定义视图:

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 不会出现在“游戏布局”中。我做错了什么?

【问题讨论】:

  • 您没有将文本视图附加到任何实际显示在屏幕上的父级!而且我不确定你想在这里做什么
  • 这就是我想要通过 gamelayout.addView(customview) 做的。至少据我所知,这将调用自定义视图的 onDraw 方法。游戏布局显示在屏幕上。
  • 你可以试试 this.addView(ll); ...在调用 ll.draw(canvas); 之前将 ll 附加到 gameLayout;

标签: android view android-canvas draw


【解决方案1】:

TextView 对象不能直接绘制到画布上,因为你已经完成了你需要分配到一个布局,然后这样做:

ll.layout(0, 0, canvas.getWidth(), canvas.getHeight()); //Modify values as needed

就我个人而言,我很惊讶调用ll.draw() 没有引发错误。除非您需要绘制 TextView,否则我更喜欢将文本绘制到画布上:

canvas.drawText(...)

See documentation here

【讨论】:

  • 不幸的是,添加此行后,仍然没有绘制任何内容:(。canvas.getWidth() 究竟返回了什么?还有其他建议吗?
  • canvas.getWidth() 应该返回您正在使用的绘图画布的宽度。如果你调试并检查你应该得到的值 > 0
【解决方案2】:

您的 LinearLayout 未附加到您的视图

尝试 this.addView(ll) 将您的 LinearLayout 添加到您的视图中。

【讨论】:

  • 您不能将View Group(例如Linear Layout)添加到视图。为此,您需要 View Group
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 2017-11-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多