0

I have created a custom view by extending the TextView widget. What it basically does is a Round view with some text above the Circle which acts as a background.

Now I need the same view again but without the text. Is there a way I can reuse the same code - instead of just copy/paste the code to create a View class without the text?

The onDraw code with the text is :

    @Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawCircle(150, 150, 150, paintBG);
    canvas.drawText("Some Text", 0, 150, textPaint);
}

EDIT : what i need is some kind of an if statement where the drawtext happens. If my view needs the text label then use the drawText. I just don't know what the condition should be since I use the code to my xml layout file.

vicolored
  • 815
  • 2
  • 10
  • 20
  • 1
    I would actually just not hardcode "some text" and make it a variable instead. Then if you want to make the text invisible either pass in a null or blank. Then simply don't draw it if it's null or blank. – DeeV Jul 17 '15 at 18:55
  • 3
    Or have a "showText" boolean value or something. There's a number of ways. – DeeV Jul 17 '15 at 18:56
  • showText is what i did and works. I added a method : public void showText(Boolean showText) { this.showText = showText; } and in onCreate I set it to false for the view i dont need the text. I just thought I could have done this in the xml code. – vicolored Jul 17 '15 at 19:09
  • You can actually do it in xml code using custom attributes. http://stackoverflow.com/questions/3441396/defining-custom-attrs – DeeV Jul 17 '15 at 19:34

1 Answers1

0

I suggest you write a custom Drawable class instead. Then you can make an instance at runtime and set it as the background of whatever View you like.

public class MyDrawable extends Drawable {

    boolean drawText;
    // other members, constructors, etc

    @Override
    public void draw(Canvas canvas) {
        canvas.drawCircle(150, 150, 150, paintBG);
        if (drawText) {
            canvas.drawText("Some Text", 0, 150, textPaint);
        }
    }

    // other methods
}

MyDrawable d = new MyDrawable();
mTextView.setBackground(d);
Karakuri
  • 38,365
  • 12
  • 84
  • 104