如何使TextInputLayout中的错误消息显示在中心位置

8

目前它的布局如附件所示:

<android.support.design.widget.TextInputLayout
    android:id="@+id/layoutCurrentPW"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    app:errorEnabled="true">

如何将“密码必须至少为8个字符”的错误消息设置为居中显示? 我尝试使用android:gravity="center",但没有效果。

enter image description here

编辑
包含EditText的布局:

<android.support.design.widget.TextInputLayout
    android:id="@+id/layoutCurrentPW"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    app:errorEnabled="true">

        <EditText
            android:id="@+id/editTextCurrentPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:layout_marginLeft="50dp"
            android:layout_marginRight="50dp"
            android:gravity="center"
            android:hint="@string/current_password"
            android:inputType="textPassword"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="@color/black" />
    </android.support.design.widget.TextInputLayout>

请查看:Material EditText - activesince93
也许可以使用类似于这个的样式来实现。 - yennsarah
7个回答

6

我想知道是否有任何方法可以从框架中处理它。似乎没有。

但TextInputLayout的工作方式是:
- 当用户触摸它时,提示将显示在EditText的顶部。
- 错误消息将显示在TextInputLayout的下方并与开头对齐。

由于我的EditText有40dp的左边距,因此提示和错误消息之间存在错位。所以现在,我从EditText中删除了40dp的左边距,并将同样的左边距应用到TextInputLayout本身,所以现在看起来很好。

得到的教训是:如果要应用任何边距到EditText中,则最好将相同的边距(如果可能)应用到TextInputLayout中,以使提示和错误消息正确放置。


3
class CenterErrorTextInputLayout(context: Context, attrs: AttributeSet) : TextInputLayout(context, attrs) {
override fun setErrorTextAppearance(resId: Int) {
    super.setErrorTextAppearance(resId)
    val errorTextView = this.findViewById<TextView>(R.id.textinput_error)
    val errorFrameLayout = errorTextView.parent as FrameLayout

    errorTextView.gravity = Gravity.CENTER
    errorFrameLayout.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
}}

复制粘贴万岁? - mrkernelpanic
对于那些没有遇到与 OP 相同问题,但实际上需要将错误消息居中并具有正常边距的人来说,这确实非常有效。 - trod

1
我通过为错误视图设置起始边距来实现它。下面是我重写的TextInputLayout组件的setError方法的版本。
@Override
public void setError(@Nullable CharSequence errorText) {
    // allow android component to create error view
    if (errorText == null) {
        return;
    }
    super.setError(errorText);
    // find this error view and calculate start margin to make it look like centered
    final TextView errorTextInput = (TextView) findViewById(R.id.textinput_error);
    errorTextInput.measure(0, 0);
    int errorWidth = errorTextInput.getMeasuredWidth();
    int layoutWidth = getWidth();
    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) errorTextInput.getLayoutParams();
    params.setMarginStart((layoutWidth - errorWidth) / 2);
    errorTextInput.setLayoutParams(params);
}

1
这里有一个解决方案,无论你的TextInputLayout有多大,它都可以始终将错误消息居中显示。
你需要创建一个从TextInputLayout继承的自定义类。然后重写ShowError(string text, Drawable icon)方法。如果出现错误,你需要将带有错误的textView居中显示。
    public class TextInputLayout_Center : TextInputLayout
    {
        public override void ShowError(string text, Android.Graphics.Drawables.Drawable icon)
        {
            base.ShowError(text, icon);

            centerErrorMessage(this);
        }

        void centerErrorMessage(ViewGroup view)
        {
            for (int i = 0; i < view.ChildCount; i++)
            {
                View v = view.GetChildAt(i);
                if (v.GetType() == typeof(TextView))
                {
                    v.LayoutParameters = new LayoutParams(ViewGroup.LayoutParams.MatchParent, v.LayoutParameters.Height);
                    ((TextView)v).Gravity = GravityFlags.CenterHorizontal;
                    ((TextView)v).TextAlignment = TextAlignment.Center;
                }
                if (v is ViewGroup)
                {
                    centerErrorMessage((ViewGroup)v);
                }
            }
        }
    }

是的,这段代码是用于Xamarin的C#编写的,但基本上是相同的。@CharlesMadere - Robin Bruneel

0

嗨,如果您正在使用最新版本的Material Design(v1.2及以上),您必须按照以下方式操作:(我将重力设置为支持RTL) 感谢@Emmanuel Guerra

class MyTextInputLayout : TextInputLayout {

    constructor(context: Context) : super(context)

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)

    constructor(context: Context, attrs: AttributeSet?, defStyleAttrs: Int) : super(context, attrs, defStyleAttrs)

    override fun setErrorEnabled(enabled: Boolean) {
        super.setErrorEnabled(enabled)
        if (!enabled) {
            return
        }
        try {
            changeTextAlignment(com.google.android.material.R.id.textinput_error, View.TEXT_ALIGNMENT_VIEW_END)
            val errorView: ViewGroup = this.getChildAt(1) as LinearLayout

            val params: LinearLayout.LayoutParams = errorView.layoutParams as LinearLayout.LayoutParams

            params.gravity = Gravity.END

            errorView.layoutParams = params
            //errorView.setPadding(0, 0, 0, 0) //use this to remove error text padding
            //setErrorIconDrawable(0)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    private fun changeTextAlignment(textViewId: Int, alignment: Int) {
        val textView = findViewById<TextView>(textViewId)
        textView.textAlignment = alignment
    }
}

0
一个自定义的TextInputLayout类,用于对齐错误文本。
class CenterErrorTextInputLayout @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0

) : TextInputLayout(context, attrs, defStyleAttr) {

    override fun setErrorEnabled(enabled: Boolean) {
        super.setErrorEnabled(enabled)

        if (!enabled) return

        try {
            setErrorTextAlignment()
        } catch (e: Exception) {
            Timber.e(e, "Failed to set error text :    RightErrorTextInputLayout")
        }
    }

    private fun setErrorTextAlignment() {
        val errorView: TextView = this.findViewById(R.id.textinput_error)
        errorView.textAlignment = View.TEXT_ALIGNMENT_CENTER
    }
}

要将文本对齐到末尾,请使用View.TEXT_ALIGNMENT_VIEW_END


0
@Override
public void setErrorEnabled(boolean enabled) {
    super.setErrorEnabled(enabled);
    if (!enabled)
        return;
    try {
        setErrorGravity(this);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private void setErrorGravity(ViewGroup view) throws Exception {
    for (int i = 0; i < view.getChildCount(); i++) {
        View errorView = view.getChildAt(i);
        if (errorView instanceof TextView) {
            if (errorView.getId() == com.google.android.material.R.id.textinput_error) {
                FrameLayout errorViewParent = (FrameLayout) errorView.getParent();
                errorViewParent.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                ((TextView) errorView).setGravity(Gravity.RIGHT);
                ((TextView) errorView).setTypeface(FontUtils.getTypeFace(view.getContext(), FontUtils.FONT_NAZANIN_TAR));
            }
        }
        if (errorView instanceof ViewGroup) {
            setErrorGravity((ViewGroup) errorView);
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接