android - NullPointer exception on Adding TextView on onDraw -


i'm trying add textview in ondraw method of mycustomview class. so, if works without issue,

tv = new textview(context); tv.settextsize(14);  tv.layout(left, top, right, bottom); tv.setgravity(gravity.center);   tv.settext(text); canvas.save();  canvas.translate(left, top); tv.draw(canvas); 

but don't want instantiate textview in ondraw. if initialize textview outside (of ondraw), in class constructor example, code work. gives me following error,

java.lang.nullpointerexception: attempt read field 'int android.view.viewgroup$layoutparams.width' on null object reference @ android.widget.textview.checkforrelayout(textview.java:8447) @ android.widget.textview.settext(textview.java:5378) @ android.widget.textview.settext(textview.java:5234) @ android.widget.textview.settext(textview.java:5191)

what reason of error?

why add textview in ondraw? there's no reason this, have horrible performance , isn't needed. if want draw text in ondraw, use canvas.drawtext(). if want add textview, in normal place. do't in rendering, part of app needs fast possible. ondraw should avoid creating objects @ if possible, less creating heavyweight view.

also, trying add view- didn't right. have add parent view, let parent layout. right after new isn't part of view hierarchy, won't draw screen. specific crash got because hasn't been added view hierarchy has no layout params. don't try fix that- don't add view here, use drawtext or add view elsewhere.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -