Invalid EditText setting ellipseze; invalid EditText setting setSelection

Requirement: edittext, one line display, no line wrapping is allowed, the longest length is 100, the cursor jumps to the end in editing status, and the ellipsis is is displayed at the end in non editing status.

Pit 1: the direct setting of ellipseze does not take effect for edittext

Pit 2: cursor jumping to the end does not take effect


Solution to pit 1: ellipseze can only take effect when setKeyListener(null), but it can't respond to any click event. Therefore, you need to get the click event of EditText first during initialization, and then assign it back when focus.

The solution of Pit 2: as soon as the focus is acquired, the cursor is set at the end, and then the cursor moves to the touch position in response to the touch acquisition focus. So you need to set a delay.

The code is for reference only. It is not easy to copy and paste directly

public class MyEditText extends AppCompatEditText implements View.OnFocusChangeListener{
  private Drawable  mClearDrawable;
  private boolean mHasFoucs = false;
  private KeyListener mListener;

  public ClearEditText (Context context) {
    this(context, null);

  public ClearEditText (Context context, AttributeSet attrs) {
    this(context, attrs, android.R.attr.editTextStyle);

  public ClearEditText (Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

public void init () {
    mHasFoucs = false;
    //Get the original KeyListener
    mListener = getKeyListener();
    //Set ellipsis at the end

@Override public void onFocusChange (View v, boolean hasFocus) {
    this.mHasFoucs = hasFocus;
    if (hasFocus) {
      //Perform positioning cursor position after 50ms
      postDelayed(() -> setSelection(getText().length(), getText().length()), 50);
      setClearIconVisible(getText().length() > 0);
      //KeyListener set back to the original KeyListener
    } else {
      //KeyListener set to null
      UIUtil.hideKeyboardFrom(getContext(), v.getWindowToken());


Tags: Android

Posted on Sun, 05 Jan 2020 18:21:59 -0800 by meshi