Подтвердить что ты не робот

Размер подсказки для Android EditText

Как уменьшить размер EditText Hint?

4b9b3361

Ответ 1

Вы можете сделать это, установив размер в исходном тексте строки.

Например:

<string name="edittext_hint"><font size="15">Hint here!</font></string>

то в вашем XML просто напишите

android:hint="@string/edittext_hint"

Это приведет к отказу в меньшем тексте для подсказки, но исходный размер для ввода текста.

Надеется, что это поможет будущим читателям

Ответ 2

Вы можете уменьшить размер шрифта на EditText, что также уменьшит размер hint. т.е. android:textSize="16sp"

Ответ 3

Мне также пришлось сделать это, так как мой намек не соответствовал EditText стандартного размера. Поэтому я сделал это (в xml задайте textSize для mHintTextSize):

MYEditText.addTextChangedListener(new TextWatcher(){

                @Override
                public void afterTextChanged(Editable arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void beforeTextChanged(CharSequence arg0, int arg1,
                        int arg2, int arg3) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onTextChanged(CharSequence arg0, int start, int before,
                        int count) {
                    if (arg0.length() == 0) { 
                        // No entered text so will show hint
                        editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, mHintTextSize);
                    } else {
                        editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, mRealTextSize);
                    }
                }
        });

Ответ 4

Вы можете установить простые атрибуты HTML для самой строки подсказки.

См. принятый ответ здесь: Подсказка Android EditText

EDIT: я просто играл с ним сам, это сработало для меня:

view.setHint(Html.fromHtml("<small><small><small>" + 
             getString(R.string.hint) + "</small></small></small>"));

Это список тегов, принятых byHtml: http://commonsware.com/blog/Android/2010/05/26/html-tags-supported-by-textview.html (хотя не работал у меня)

Ответ 5

Если вы хотите сделать это программно,

SpannableString span = new SpannableString(strHint);
span.setSpan(new RelativeSizeSpan(0.5f), 0, strHint.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
editText.setHint(span);

Ответ 6

легко уменьшить размер подсказки edittext

editText.setHint(Html.fromHtml(
    "<font size=\"5\">" + "hinttext1" + "</font>" + 
    "<small>" + "hinttext2" + "</small>" )); 

Ответ 7

@marmor Подход - лучший. Вы можете изменить количество тегов <small> --- </small> для настройки размера.

Вы также можете определить текст подсказки напрямую, как я сделал

view.setHint(Html.fromHtml("<small><small><small>" + "This is Hint" + "</small></small></small>"));

Надеюсь, это поможет.

Ответ 8

@user2982553 решение отлично работает для меня. Вы также можете использовать AbsoluteSizeSpan, с помощью которого вы можете установить точный размер шрифта подсказки. Не используйте тег <font size=\"5\">, потому что атрибут size просто игнорируется.

Ответ 9

Мне нужно установить больший размер для реального текста, чем подсказку.

public static class LargeSizeTextWatcher implements TextWatcher {

    private final EditText mEditText;
    private final int mOriginalSize;
    private final int mLargeSize;

    private int mLastLength;

    TrackingNumberTextWatcher(EditText editText) {
        mEditText = editText;
        mOriginalSize = (int) editText.getTextSize();
        mLargeSize = editText.getResources().getDimensionPixelSize(R.dimen.text_size_large);

        mLastLength = editText.length();
        if (mLastLength != 0) {
            mEditText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mLargeSize);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        int length = s.length();
        if (length == 0) {
            mEditText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mOriginalSize);
        } else if (mLastLength == 0) {
            mEditText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mLargeSize);
        }
        mLastLength = length;
    }
}

Ответ 10

Вы можете изменить не только размер подсказки, но и шрифт и стиль. Я решил решить его с помощью SpannableString и MetricAffectingSpan

1) Создайте пользовательский объект Hint:

import android.graphics.Typeface;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.MetricAffectingSpan;

public class CustomHint extends SpannableString
{
    public CustomHint(final CharSequence source, final int style)
    {
        this(null, source, style, null);
    }

    public CustomHint(final CharSequence source, final Float size)
    {
        this(null, source, size);
    }

    public CustomHint(final CharSequence source, final int style, final Float size)
    {
        this(null, source, style, size);
    }

    public CustomHint(final Typeface typeface, final CharSequence source, final int style)
    {
        this(typeface, source, style, null);
    }

    public CustomHint(final Typeface typeface, final CharSequence source, final Float size)
    {
        this(typeface, source, null, size);
    }

    public CustomHint(final Typeface typeface, final CharSequence source, final Integer style, final Float size)
    {
        super(source);

        MetricAffectingSpan typefaceSpan = new CustomMetricAffectingSpan(typeface, style, size);
        setSpan(typefaceSpan, 0, source.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    }
}

2) Создайте собственный объект MetricAffectingSpan:

import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.style.MetricAffectingSpan;

public class CustomMetricAffectingSpan extends MetricAffectingSpan
{
    private final Typeface _typeface;
    private final Float    _newSize;
    private final Integer  _newStyle;

    public CustomMetricAffectingSpan(Float size)
    {
        this(null, null, size);
    }

    public CustomMetricAffectingSpan(Float size, Integer style)
    {
        this(null, style, size);
    }

    public CustomMetricAffectingSpan(Typeface type, Integer style, Float size)
    {
        this._typeface = type;
        this._newStyle = style;
        this._newSize = size;
    }

    @Override
    public void updateDrawState(TextPaint ds)
    {
        applyNewSize(ds);
    }

    @Override
    public void updateMeasureState(TextPaint paint)
    {
        applyNewSize(paint);
    }

    private void applyNewSize(TextPaint paint)
    {
        if (this._newStyle != null)
            paint.setTypeface(Typeface.create(this._typeface, this._newStyle));
        else
            paint.setTypeface(this._typeface);

        if (this._newSize != null)
            paint.setTextSize(this._newSize);
    }
}

3) Использование:

Typeface newTypeface = Typeface.createFromAsset(getAssets(), "AguafinaScript-Regular.ttf");
CustomHint customHint = new CustomHint(newTypeface, "Enter some text", Typeface.BOLD_ITALIC, 60f);
        //        CustomHint customHint = new CustomHint(newTypeface, "Enter some text", Typeface.BOLD_ITALIC);
        //        CustomHint customHint = new CustomHint(newTypeface, "Enter some text", 60f);
        //        CustomHint customHint = new CustomHint("Enter some text", Typeface.BOLD_ITALIC, 60f);
        //        CustomHint customHint = new CustomHint("Enter some text", Typeface.BOLD_ITALIC);
        //        CustomHint customHint = new CustomHint("Enter some text", 60f);

customEditText.setHint(customHint);

Ответ 11

Использование onFocusChanged() слушателя для изменения размера шрифта подсказки также является опцией, так как addTextChangeListener() не сработает, когда пользователь нажимает на текстовое поле, а мигающий курсор изменит размер шрифта подсказки.

Кроме того, в отличие от TextChangeListener, нет необходимости устанавливать начальный размер шрифта подсказки отдельно.

class EditTextWithHintSize {
 init {
        val typedArray = context.obtainStyledAttributes(attrs,
                R.styleable.EditTextWithHintSize, 0, defStyle)
        try {
            hintFontSize = typedArray.getDimension(R.styleable.EditTextWithHintSize_hint_font_size, textSize)
            fontSize = textSize

            if (length() == 0) {
                setTextSize(TypedValue.COMPLEX_UNIT_PX, hintFontSize)
            }
        } catch (e: Exception) {
            hintFontSize = textSize
            fontSize = textSize
        } finally {
            typedArray.recycle()
        }
    }

    override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect)

        if (focused) {
            setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize)
        } else {
            if (length() == 0) {
                setTextSize(TypedValue.COMPLEX_UNIT_PX, hintFontSize)
            } else {
                setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize)
            }
        }
    }
}