how to make hint disappear when edittext is touched?

后端 未结 12 1147
青春惊慌失措
青春惊慌失措 2020-12-14 00:39

In my application in android are many EditText fields. And I ran into a problem with hint. It is not disappearing when EditText is focused, but it disappears when I start to

12条回答
  •  北海茫月
    2020-12-14 01:13

    The proposed selector solution by windyzboy doesn't work for EditTexts with centered text, because the cursor stays behind the transparent hint text instead of moving to the center.

    A good way without polluting your code is to make a custom EditText, since you probably need the same style in the whole application. That way you can avoid adding checks for each EditText separately.

    public class HideHintEditText extends EditText {
    
        CharSequence hint;
    
        public HideHintEditText(Context context) {
            super(context);
            hint = this.getHint();
        }
    
        public HideHintEditText(Context context, AttributeSet attrs) {
            super(context, attrs);
            hint = this.getHint();
        }
    
        public HideHintEditText(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            hint = this.getHint();
        }
    
        @Override
        protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
            super.onFocusChanged(focused, direction, previouslyFocusedRect);
    
            this.setHint(focused ? "" : hint);
        }
    
    }
    

提交回复
热议问题