EditText 游標定位 (當內容在右邊時,游標在hint左邊的問題)
阿新 • • 發佈:2018-12-19
解決EditText游標定位問題
需求:
有時候我們的需求是讓輸入從右邊開始,如下圖,這是產品和ux需要的
在正常的通過xml佈局後,在有的機型上可能顯示為:| Hometown
有些是設定屬性的方式來修改這個bug,但是比較穩妥的是自己定義一個EditText,自己畫一個Cursor
如下程式碼,直接copy進專案可直接使用:
public class CursorEditText extends AppCompatEditText { private CharSequence mHint; private Paint mPaint; private int mHintTextColor; public CursorEditText(Context context) { this(context, null); } public CursorEditText(Context context, AttributeSet attrs) { this(context, attrs, android.support.v7.appcompat.R.attr.editTextStyle); } public CursorEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs, defStyleAttr); } private void init(Context context, AttributeSet attrs, int defStyleAttr) { mHint = getHint(); setHint(""); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG); mPaint.setTextSize(getTextSize()); mPaint.setTextAlign(Paint.Align.RIGHT); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (TextUtils.isEmpty(mHint) || !TextUtils.isEmpty(getText())) { return; } canvas.save(); ColorStateList hintTextColors = getHintTextColors(); if (hintTextColors != null) { int color = hintTextColors.getColorForState(getDrawableState(), 0); if (color != mHintTextColor) { mHintTextColor = color; mPaint.setColor(color); } } Paint.FontMetricsInt fontMetrics = mPaint.getFontMetricsInt(); int baseline = (getHeight() - fontMetrics.bottom + fontMetrics.top) / 2 - fontMetrics.top; canvas.drawText(mHint, 0, mHint.length(), getWidth() - getPaddingRight() + getScrollX(), baseline, mPaint); canvas.restore(); } }