解决方案看这篇文章,原理是用一个TextView代替hint。解决EditText文字右对齐时光标出现在hint文字的左边的问题
因为项目中也遇到了这个问题,所以将这个方法写成了一个自定义控件方便使用。
/**
* Created by AItsuki on 2018/3/13.
*
* hintView可能不能完全和EditText契合。
* 因为这里很难复制EditText的所有属性, 比如是否设置了SingleLine可能需要反射才能获取这个属性值。
*/
public class FixCursorLayout extends FrameLayout {
private TextView hintView;
public FixCursorLayout(Context context) {
this(context, null);
}
public FixCursorLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FixCursorLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
super.addView(child, index, params);
if (child instanceof EditText) {
int gravity = ((EditText) child).getGravity() & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK;
if (gravity == Gravity.END || gravity == Gravity.RIGHT) {
setEditText((EditText) child);
}
}
}
private void setEditText(EditText editText) {
hintView = new TextView(getContext());
hintView.setTextColor(editText.getHintTextColors());
hintView.setText(editText.getHint());
hintView.setTextSize(TypedValue.COMPLEX_UNIT_PX, editText.getTextSize());
hintView.setPadding(editText.getPaddingLeft(), editText.getPaddingTop(),
editText.getPaddingRight(), editText.getPaddingBottom());
hintView.setGravity(editText.getGravity());
addView(hintView, editText.getLayoutParams());
editText.setHint("");
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (TextUtils.isEmpty(s)) {
hintView.setVisibility(VISIBLE);
} else {
hintView.setVisibility(GONE);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
}
使用方式,在EditText外面套一层FixCursorLayout即可。
<xxx.xxx.xxx.FixCursorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@null"
android:gravity="center_vertical|right|end"
android:hint="@string/please_input"
android:inputType="phone"
android:maxLength="11"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:singleLine="true"
android:textColor="@color/black_90p"
android:textColorHint="@color/black_30p"
android:textSize="@dimen/font_16" />
</xxx.xxx.xxx.FixCursorLayout>