How to change hint text size without changing the text size in EditText

前端 未结 4 922
傲寒
傲寒 2021-02-07 08:23

I have a EditText input field. I have added a hint in it. Now i want to change the size of hint text, but when i do this, it also effects the size of the text. Kind

4条回答
  •  广开言路
    2021-02-07 09:22

    The hint and the text are exclusive, if one of them is visible, the other one is not.

    Because of this, you could just change the attributes of your EditText depending on if it's empty (the hint is visible) or not (the text is visible).

    For example:

    final EditText editText = (EditText) findViewById(R.id.yourEditText);
    
    editText.addTextChangedListener(new TextWatcher() {
        boolean hint;
    
        @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(s.length() == 0) {
                // no text, hint is visible
                hint = true;
                editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                editText.setTypeface(Typeface.createFromAsset(getAssets(),
                    "hintFont.ttf")); // setting the font
            } else if(hint) {
                // no hint, text is visible
                hint = false;
                editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                editText.setTypeface(Typeface.createFromAsset(getAssets(),
                    "textFont.ttf")); // setting the font
            }
        }
    
        @Override
        public void afterTextChanged(Editable s) {
        }
    });
    

提交回复
热议问题