Search code examples
androidbuttontextviewandroid-custom-view

How to make a Button from a custom TextView?


I'm trying to make a simple buttom by extending a TextView but if I draw the button's surface, it draws over the text so the text hides. How can I draw it behind the text?. This is my class

public class DoodleButton extends TextView{

private float rx = 5f;
private float ry = 5f;
private float viewWidth, viewHeight;
private float positionX = 0, positionY = 0;
private Paint paintButton = new Paint();
private RectF area;

public DoodleButton(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(attrs, 0);

    TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.DoodleButton, 0,0);

    try{
        rx = a.getFloat(R.styleable.DoodleButton_rx, 5f);
        ry = a.getFloat(R.styleable.DoodleButton_ry, 5f);
    }finally {
        a.recycle();
    }
}

private void init(AttributeSet attrs, int defStyle){
    paintButton.setColor(Color.GRAY);
    paintButton.setAntiAlias(false);
}

@Override
protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld){
    super.onSizeChanged(xNew, yNew, xOld, yOld);
    viewWidth = xNew;
    viewHeight = yNew;
    area = new RectF(0,0, viewHeight, viewHeight);
}

@Override
public void onDraw(Canvas canvas){
    super.onDraw(canvas);
    canvas.drawRoundRect(area, 5, 5, paintButton);
}
}

When I draw the roundRect it overlaps the text in the textView and I would like to make the button draw behind the text.


Solution

  • If you want a TextView to be used as a button just add onClickListener to the view.

    and if you want to design it so i will change to background color ontouch event use "onTouchListener".