Як зменшити EditTextрозмір підказки?
Як зменшити EditTextрозмір підказки?
Відповіді:
Це можна зробити, встановивши розмір у джерелі рядків.
Наприклад:
<string name="edittext_hint"><font size="15">Hint here!</font></string>
тоді у своєму XML просто напишіть
android:hint="@string/edittext_hint"
Це призведе до зменшення тексту для підказки, але оригінального розміру для вхідного тексту.
Сподіваюся, це допоможе майбутнім читачам
spрозмір для sizeатрибута?
Ви можете зменшити розмір шрифту на EditText-, що також зменшить розмір шрифту hint. тобтоandroid:textSize="16sp"
Мені також довелося це зробити, оскільки мій підказка не вмістилася в 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);
}
}
});
TextWatcherви можете просто зателефонувати editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, mRealTextSize);негайно. Однак рішення longhairedsi може бути більш безпечним у майбутньому. Мені цікаво, чи ця проблема буде вирішена в нових версіях SDK.
Ви можете встановити прості атрибути HTML для самого рядка підказки.
Дивіться прийняту відповідь тут: Підказка Android EditText
РЕДАКТУВАТИ: просто грався з цим сам, це працювало для мене:
view.setHint(Html.fromHtml("<small><small><small>" +
getString(R.string.hint) + "</small></small></small>"));
Це список тегів, прийнятих fromHtml: http://commonsware.com/blog/Android/2010/05/26/html-tags-supported-by-textview.html (хоча у мене не працював)
Якщо ви хочете зробити це програмно,
SpannableString span = new SpannableString(strHint);
span.setSpan(new RelativeSizeSpan(0.5f), 0, strHint.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
editText.setHint(span);
Підхід @marmor - найкращий. Ви можете змінити кількість <small> --- </small>тегів, щоб відрегулювати розмір.
Ви також можете визначити текст підказки безпосередньо, як я це зробив
view.setHint(Html.fromHtml("<small><small><small>" +
"This is Hint" + "</small></small></small>"));
Сподіваюся, це допоможе.
визначте це у своєму strings.xml у папці значень:
<string name="enter_otp"><font size="16">your text</font></string>
Мені потрібно встановити більший розмір для реального тексту, ніж підказка.
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;
}
}
Ви можете змінити не лише розмір підказки, але також його шрифт та стиль. Я досяг її вирішити з допомогою 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);
Використання прослуховувача 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)
}
}
}
}