简体   繁体   中英

How to change the editText line colors programmatically?

I use this class to make lines inside editText which works well. I want to change the line colors in another activities programmatically. How to do that?

public  class LinedEditText extends androidx.appcompat.widget.AppCompatEditText{
    public final Paint mPaint = new Paint();

    public LinedEditText(Context context) {
        super(context);
        initPaint();
    }

    public LinedEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        initPaint();
    }

    public LinedEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initPaint();
    }

    private void initPaint() {
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(Color.BLUE);
    }

    @Override protected void onDraw(Canvas canvas) {
        int left = getLeft();
        int right = getRight();
        int paddingTop = getPaddingTop();
        int paddingBottom = getPaddingBottom();
        int paddingLeft = getPaddingLeft();
        int paddingRight = getPaddingRight();
        int height = getHeight();
        int lineHeight = getLineHeight();
        int count = (height-paddingTop-paddingBottom) / lineHeight;

        for (int i = 0; i < count; i++) {
            int baseline = lineHeight * (i+1) + paddingTop;
            canvas.drawLine(left+paddingLeft, baseline, right-paddingRight, baseline, mPaint);
        }

        super.onDraw(canvas);
    }
}

Second question is, how to make new line when the user pressed enter or return key so as to the will have something like unlimited lines?

public  class LinedEditText extends EditText {

private Rect mRect;
protected Paint mPaint;

// we need this constructor for LayoutInflater
public LinedEditText(Context context, AttributeSet attrs) {
    super(context, attrs);

    mRect = new Rect();
    mPaint = new Paint();
    mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
    mPaint.setColor(Color.parseColor("#82B6C6"));
}

@Override
public void onDraw(Canvas canvas) {
    //int count = getLineCount();

    int height = getHeight();
    int line_height = getLineHeight();

    int count = height / line_height;

    if (getLineCount() > count)
        count = getLineCount();//for long text with scrolling


    Rect r = mRect;
    Paint paint = mPaint;
    int baseline = getLineBounds(0, r);//first line

    for (int i = 0; i < count; i++) {

        canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
        baseline += getLineHeight();//next line
    }

    super.onDraw(canvas);
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM