自动调整EditText

时间:2017-11-01 11:31:14

标签: android android-edittext autosize

Android最近添加了对基于视图大小和最小和最大文本大小调整TextViews文本大小的支持。
https://developer.android.com/guide/topics/ui/look-and-feel/autosizing-textview.html

不幸的是,他们不支持EditTexts,那么EditText还有其他选择吗?

4 个答案:

答案 0 :(得分:4)

我被困在你身边,EditText是TextView的孩子,但不支持自动调整????

我通过某种黑客实现了这一目标。 首先,我看到TextView代码在EditTextView上复制并实现为扩展(在Kotlin中),但是......有很多方法,所以最后我放弃了该选项。

我做了什么,使用TextView是不可见的(是的,我知道这是一个完整的黑客,对此不是很满意,但谷歌应该为此感到羞耻)

这是我的xmls

    <TextView android:id="@+id/invisibleTextView"
    android:layout_height="0dp"
    android:layout_width="match_parent"
    android:focusable="false"
    app:autoSizeTextType="uniform"
    app:autoSizeMinTextSize="@dimen/text_min"
    app:autoSizeMaxTextSize="@dimen/text_max"
    app:autoSizeStepGranularity="@dimen/text_step"
    android:textAlignment="center"
    app:layout_constraintLeft_toLeftOf="@id/main"
    app:layout_constraintRight_toRightOf="@id/main"
    app:layout_constraintTop_toBottomOf="@id/textCount"
    app:layout_constraintBottom_toBottomOf="@id/main"
    android:visibility="invisible"
    tool:text="This is a Resizable Textview" />


<EditText android:id="@+id/resizableEditText"
    android:layout_height="0dp"
    android:layout_width="match_parent"
    android:textAlignment="center"
    app:layout_constraintLeft_toLeftOf="@id/main"
    app:layout_constraintRight_toRightOf="@id/main"
    app:layout_constraintTop_toBottomOf="@id/textCount"
    app:layout_constraintBottom_toBottomOf="@id/main"
    android:maxLength="@integer/max_text_length"
    tool:text="This is a Resizable EditTextView" />

注意:两个视图都具有相同的宽度/高度

非常重要

然后在我的代码中,我使用此textview中的自动计算在我的EditTextView上使用。

private fun setupAutoresize() {
    invisibleTextView.setText("a", TextView.BufferType.EDITABLE) //calculate the right size for one character
    resizableEditText.textSize = autosizeText(invisibleTextView.textSize)
    resizableEditText.setHint(R.string.text_hint)

    resizableEditText.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(editable: Editable?) {
            resizableEditText.textSize = autosizeText(invisibleTextView.textSize)
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            textCount.text = currentCharacters.toString()
            val text = if (s?.isEmpty() ?: true) getString(R.string.text_hint) else s.toString()
            invisibleTextView.setText(text, TextView.BufferType.EDITABLE)
        }
    })
}

private fun autosizeText(size: Float): Float {
    return size / (resources.displayMetrics.density + MARGIN_FACTOR /*0.2f*/)
}

请注意,要更改提示的大小,请使用此Android EditText Hint Size

我知道这是一个艰难的解决方法,但至少我们确信即使在未来版本上进行可调整大小的更改时,这仍将继续有效,而一个可靠的或遗弃的github lib将失败。

我希望有一天,谷歌听到我们并在孩子们身上实施这个精彩的功能,我们可以避免所有这些东西

希望这有帮助

答案 1 :(得分:1)

此库基于:

AutoFitTextView https://github.com/ViksaaSkool/AutoFitEditText 请试试这个

答案 2 :(得分:0)

您可以尝试使用我的 AutoSizeEditText

   /**
 * Wrapper class for {@link EditText}.
 * It helps to achieve auto size behaviour which exists in {@link AppCompatTextView}.
 * The main idea of getting target text size is measuring {@link AppCompatTextView} and then
 * extracting from it text size and then applying extracted text size to target {@link EditText}.
 */
public class AutoSizeEditText extends FrameLayout {

    private static final String TEST_SYMBOL = "T";

    private static final boolean TEST = false;

    /**
     * Vertical margin which is applied by default in {@link EditText} in
     * comparison to {@link AppCompatTextView}
     */
    private static final float VERTICAL_MARGIN = convertDpToPixel(4);

    /**
     * {@link TextMeasure} which helps to get target text size for {@link #wrappedEditTex}
     * via its auto size behaviour.
     */
    @NonNull
    private final TextMeasure textMeasurer;

    /**
     * {@link AppCompatEditText} we want to show to the user
     */
    @NonNull
    private final EditText wrappedEditTex;

    public AutoSizeEditText(Context context) {
        this(context, null);
    }

    public AutoSizeEditText(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AutoSizeEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        // don't clip children
        setClipChildren(false);
        setClipToOutline(false);
        setClipToPadding(false);

        // using AttributeSet of TextView in order to apply it our text views
        wrappedEditTex = createWrappedEditText(context, attrs);

        textMeasurer = createTextMeasure(context, attrs, wrappedEditTex);

        addView(wrappedEditTex, new FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT));

        addView(textMeasurer, new FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT));
    }

    @NonNull
    private TextMeasure createTextMeasure(Context context, AttributeSet attrs, EditText editText) {
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.AutoSizeEditText);
        final int minSize = (int) typedArray.getDimension(R.styleable.AutoSizeEditText_autoSizeMinTextSize, convertDpToPixel(10));
        final int maxSize = (int) typedArray.getDimension(R.styleable.AutoSizeEditText_autoSizeMaxTextSize, convertDpToPixel(18));
        final int step = (int) typedArray.getDimension(R.styleable.AutoSizeEditText_autoSizeStepGranularity, convertDpToPixel(1));
        typedArray.recycle();

        TextMeasure textMeasurer = new TextMeasure(context);
        final Editable text = editText.getText();
        final CharSequence hint = editText.getHint();
        if (!TextUtils.isEmpty(text)) {
            textMeasurer.setText(text);
        } else if (!TextUtils.isEmpty(hint)) {
            textMeasurer.setText(hint);
        } else {
            textMeasurer.setText(TEST_SYMBOL);
        }

        TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(
                textMeasurer, minSize, maxSize, step, TypedValue.COMPLEX_UNIT_PX);

        textMeasurer.setVisibility(View.INVISIBLE);
        textMeasurer.setPadding(0, 0, 0, 0);
        if (TEST) {
            textMeasurer.setTextColor(Color.RED);
            final ColorDrawable background = new ColorDrawable(Color.YELLOW);
            background.setAlpha(50);
            textMeasurer.setBackground(background);
            textMeasurer.setAlpha(0.2f);
            textMeasurer.setVisibility(View.VISIBLE);
        }
        return textMeasurer;
    }

    /**
     * Creating {@link EditText} which user will use and see
     *
     * @param attrs {@link AttributeSet} which comes from most likely from xml, which can be user for {@link EditText}
     *              if attributes of {@link TextView} were declared in xml
     * @return created {@link EditText}
     */
    @NonNull
    protected EditText createWrappedEditText(Context context, AttributeSet attrs) {
        return new AppCompatEditText(context, attrs);
    }

    @NonNull
    public EditText getWrappedEditTex() {
        return wrappedEditTex;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);

        wrappedEditTex.measure(
                MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
                MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));

        final int targetHeight = (int) (height
                - VERTICAL_MARGIN * 2
                - wrappedEditTex.getPaddingTop()
                - wrappedEditTex.getPaddingBottom());

        final int targetWidth = (width
                - wrappedEditTex.getTotalPaddingStart()
                - wrappedEditTex.getTotalPaddingEnd());

        textMeasurer.measure(
                MeasureSpec.makeMeasureSpec(targetWidth, MeasureSpec.EXACTLY),
                MeasureSpec.makeMeasureSpec(targetHeight, MeasureSpec.EXACTLY)
        );

        setMeasuredDimension(width, height);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        final int layoutHeight = getMeasuredHeight();
        final int layoutWidth = getMeasuredWidth();

        wrappedEditTex.layout(0, 0, layoutWidth, layoutHeight);

        if (changed) {
            final int measuredHeight = textMeasurer.getMeasuredHeight();
            final int measuredWidth = textMeasurer.getMeasuredWidth();
            final int topCoordinate = (int) (wrappedEditTex.getPaddingTop() + VERTICAL_MARGIN);
            final int leftCoordinate = wrappedEditTex.getTotalPaddingStart();

            textMeasurer.layout(
                    leftCoordinate,
                    topCoordinate,
                    measuredWidth + leftCoordinate,
                    topCoordinate + measuredHeight);

            wrappedEditTex.setTextSize(TypedValue.COMPLEX_UNIT_PX, textMeasurer.getTextSize());
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return wrappedEditTex.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return wrappedEditTex.onTouchEvent(event);
    }

    /**
     * Adjust text size due to the fact we want hint to be always visible
     *
     * @param hint Hint for {@link #wrappedEditTex}
     */
    public void setHint(CharSequence hint) {
        wrappedEditTex.setHint(hint);
        textMeasurer.setText(hint);
    }

    /**
     * Adjust text size for TypeFace, because it can change calculations
     *
     * @param typeface for {@link #wrappedEditTex}
     */
    public void setTypeface(Typeface typeface) {
        wrappedEditTex.setTypeface(typeface);
        textMeasurer.setTypeface(typeface);
    }

    public void setTextColor(Integer textColor) {
        wrappedEditTex.setTextColor(textColor);
    }

    public void setHintTextColor(Integer hintTextColor) {
        wrappedEditTex.setHintTextColor(hintTextColor);
    }

    public void setText(CharSequence text) {
        wrappedEditTex.setText(text);
    }

    private static class TextMeasure extends AppCompatTextView {

        public TextMeasure(Context context) {
            super(context);
        }

        @Override
        public void setInputType(int type) {

        }

        @Override
        public void setRawInputType(int type) {

        }

        @Override
        public int getInputType() {
            return EditorInfo.TYPE_NULL;
        }

        @Override
        public int getMaxLines() {
            return 1;
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            return true;
        }

        @Override
        public int getMinLines() {
            return 1;
        }
    }
}

使用我的组件的示例如下:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.vladislavkarpman.autosizeedittext.AutoSizeEditText
        android:layout_width="300dp"
        android:layout_height="100dp"
        app:autoSizeMaxTextSize="50dp"
        app:autoSizeMinTextSize="4dp"
        app:autoSizeStepGranularity="1dp"
        app:autoSizeTextType="uniform"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

答案 3 :(得分:0)

您可以使用 RelativeLayout 将 TextView 隐藏在 EditText 后面,这两者的高度和宽度相同。 TextView 将有 android:autoSizeTextType="uniform" 通过在 EditText 上使用 setOnTextChangedListener,您可以将 TextView 的文本设置为 EditText 中的任何内容。然后TextView的文字大小会自动调整。然后,您必须将 EditText 的文本大小设置为与 TextView 的文本大小相同。这是布局:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"

android:layout_height="match_parent" tools: context=".MainActivity">

<TextView

android:id="@+id/test"

android:layout_width="match_parent" android:layout_height="match_parent" android:padding="0dp"

android:layout_margin="0dp"

android: autoSizeTextType="uniform"

android: autosizeMaxTextSize="500sp" android: autosizestepGranularity="1sp"/>

<EditText

android:id="@+id/edit"

android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="0dp"/>

android:padding="0dp"

</RelativeLayout>

和代码:

public void code(){

edit.setMovement Method (null);

edit.addTextChangedListener(new Textwatcher() {

@Override

public void onTextChanged (CharSequence s, int start, int before, int count) { test.setText (edit.getText().tostring()); edit.setTextSize(pixel2dip(test.getTextSize()));

}

public static float pixel2dip(float a) {

int b = (int) (a);

int c = (int) (b / Resources.getSystem().getDisplayMetrics ().scaledDensity); return (float) (c);

});

}