输入字体带有描边效果的EditText

  • 实现效果:EditText在输入时,字体带有描边效果。
  • 实现的原理很简单,其实就是在EditText中嵌入一个带描边效果的EditText。(网上很多文章都是TextView,但是实测TextView在输入英文时,两者的换行效果不一致,会出现错位的问题。)
public class StrokeEditText extends AppCompatEditText {

    private EditText outlineTextView;
    private int strokeColor;

    public StrokeEditText(Context context) {
        super(context);
        outlineTextView = new EditText(context);
        init();
    }

    public StrokeEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        outlineTextView = new EditText(context, attrs);
        init();
    }

    public StrokeEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        outlineTextView = new EditText(context, attrs, defStyle);
        init();
    }

    public void init() {
        outlineTextView.setEnabled(false);
        strokeColor = getContext().getResources().getColor(R.color.white);
        TextPaint paint = outlineTextView.getPaint();
        paint.setStrokeWidth(4f);
        paint.setStyle(Paint.Style.STROKE);
        outlineTextView.setTextColor(strokeColor);
        outlineTextView.setHintTextColor(strokeColor);
        outlineTextView.setGravity(getGravity());
    }

    @Override
    public void setLayoutParams(ViewGroup.LayoutParams params) {
        super.setLayoutParams(params);
        outlineTextView.setLayoutParams(params);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 设置轮廓文字
        CharSequence outlineText = outlineTextView.getText();
        if (outlineText == null || !outlineText.equals(this.getText())) {
            outlineTextView.setText(getText());
            postInvalidate();
        }
        outlineTextView.measure(widthMeasureSpec, heightMeasureSpec);

        CharSequence hint = outlineTextView.getHint();

        if (hint == null || !hint.equals(this.getHint())) {
            outlineTextView.setHint(getHint());
            postInvalidate();
        }
        outlineTextView.measure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        outlineTextView.layout(left, top, right, bottom);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        outlineTextView.draw(canvas);
        super.onDraw(canvas);
    }

    @Override
    protected void onScrollChanged(int horiz, int vert, int oldHoriz, int oldVert) {
        super.onScrollChanged(horiz, vert, oldHoriz, oldVert);
        outlineTextView.scrollTo(horiz, vert);
    }
}

注意:要监听EditText的滚动变化,在EditText输入内容较多,用户手动滚动EditText时,能够让描边的字体也滚动到指定位置。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容