1

如何将错误文本消息对齐到edittext的中心和下方。我尝试对齐但它不起作用。这是我的代码:

在此处输入图像描述

xml

<android.support.design.widget.TextInputLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/tilEmail">
 <EditText
                    android:layout_width="match_parent"
                    android:id="@+id/mob"
                    android:layout_height="35dp"
                    android:background="@drawable/round_corner_3"
                    android:inputType="phone"
                    android:hint="Mobile Number"
                    android:textColorHint="@color/colorGray"
                    android:textColor="@color/Black"
                        android:drawablePadding="10dp"/>
                </android.support.design.widget.TextInputLayout>

Java 类

til = (TextInputLayout) findViewById(R.id.tilEmail);

                     til.setError("Mobile number not valid");

                     til.setError(Html.fromHtml("<font color='red'>Mobile number not valid</font>"));
                    mobile.setError(null);

         mobile.getBackground().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
                    Toast.makeText(getApplicationContext(), "Phone number or Password is not valid", Toast.LENGTH_SHORT).show();

                }
4

2 回答 2

1
// reference an error textview
TextView textView = (TextView) til.findViewById(android.support.design.R.id
            .textinput_error);

if (textView != null) {
    // can be RelativeLayout/FrameLayout Params, depending on your xml
    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) textView.getLayoutParams();
    params.gravity = Gravity.CENTER|Gravity.BOTTOM;
    textView.setLayoutParams(params);
}

此外,您可以将边距添加到LayoutParams

于 2019-02-14T11:33:17.970 回答
0

您需要创建一个自定义类扩展TextInputLayout并在那里设置重力。R.id.textinput_error_text这是因为在先前设置错误之前您无法获取id。

使用 Kotlin:

class TextInputLayoutErrorEnd(context: Context, attrs: AttributeSet) :
    TextInputLayout(context, attrs) {
    override fun setError(errorText: CharSequence?) {
        super.setError(errorText)
        errorText?.let {
            val errorTextView = findViewById<TextView>(R.id.textinput_error_text)
            errorTextView.gravity = Gravity.END
        }
    }
}

在您的 XML 上:

<package.TextInputLayoutErrorEnd...>
    <com.google.android.material.textfield.TextInputEditText.../>
</package.TextInputLayoutErrorEnd>
于 2021-08-19T17:55:50.957 回答