Philipp Jahoda
Philipp Jahoda

Reputation: 51421

Android draw TextView from CustomView

I have a customview looking like this:

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

And in my main activity, I do this:

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

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

My problem is, that simply nothing is drawn, the drawn TextView does not appear in the "gamelayout". What am I doing wrong?

Upvotes: 1

Views: 6172

Answers (2)

MrZander
MrZander

Reputation: 3120

Your LinearLayout isn't attached to your view

try this.addView(ll) to add your LinearLayout to your view.

Upvotes: 1

Grambot
Grambot

Reputation: 4524

TextView objects are not able to draw directly to the canvas, as you've done you need to assign to a Layout and then do this:

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

Personally, I'm surprised there aren't errors thrown for calling ll.draw(). Unless you have a need to drawing a TextView I prefer drawing the text to the canvas:

canvas.drawText(...)

See documentation here

Upvotes: 1

Related Questions