如何从自定义 TextView 制作按钮?

How to make a Button from a custom TextView?

我试图通过扩展 TextView 来制作一个简单的按钮,但如果我绘制按钮的表面,它会覆盖文本,因此文本会隐藏。我怎样才能把它画在文字后面?这是我的 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);
}
}

当我绘制 roundRect 时,它与 textView 中的文本重叠,我想让按钮绘制在文本后面。

如果您希望将 TextView 用作按钮,只需将 onClickListener 添加到视图即可。

如果你想设计它,我会在触摸事件使用 "onTouchListener" 时更改为背景颜色。

我不会费心使用 TextView 子类,而是按照您想要的方式使用 Button directly. You can style them

如果您需要做一些 Button 做不到的事情,那么制作一个自定义视图并按照您想要的方式将所有内容绘制到 Canvas 中。