Ответ 1
if (TextUtils.isEmpty(userName)) {
register_UserName_layout.setError("Insert Username");
txtInpit.setColorFilter(R.color.white);
}
Я хочу setError
когда TextInputLayout
isEmpty
, я пишу этот код, но когда setError
сообщение об ошибке, установите красный фон для TextInputLayout
!
Я не хочу устанавливать фон! Я хочу просто показать сообщение об ошибке.
Мой код:
if (TextUtils.isEmpty(userName)) {
register_UserName_layout.setError("Insert Username");
}
XML-код:
<android.support.design.widget.TextInputLayout
android:id="@+id/register_userUsernameTextLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/register_headerLayout"
android:layout_margin="10dp"
android:textColorHint="#c5c5c5">
<EditText
android:id="@+id/register_userUserNameText"
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="@drawable/selector_bg_edit"
android:hint="نام کاربری"
android:paddingBottom="2dp"
android:textColor="@color/colorAccent"
android:textCursorDrawable="@drawable/bg_input_cursor"
android:textSize="16sp" />
</android.support.design.widget.TextInputLayout>
Как я могу это исправить? Спасибо всем <3
if (TextUtils.isEmpty(userName)) {
register_UserName_layout.setError("Insert Username");
txtInpit.setColorFilter(R.color.white);
}
Я нашел обходной путь к этой проблеме. Вам просто нужно создать настраиваемый EditText и переопределить метод getBackground(), чтобы вернуть новый drawable. Таким образом, TextInputLayout не сможет установить цветной фильтр на фоне EditText, так как вы не возвращаете фон EditText, а некоторые другие. См. Ниже:
@Override
public Drawable getBackground() {
return ContextCompat.getDrawable(getContext(), R.drawable.some_drawable);
}
и используйте пользовательский EditText внутри TextInputLayout:
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CustomEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/custom_edit_text_bg" />
</android.support.design.widget.TextInputLayout>
Суть этой проблемы в том, что у вашего EditText установлен цвет фона. Если это так, удалите его и поместите цвет фона на свой текстовый виджет "Макет ввода". Это решит проблему большой красной коробки. По крайней мере, для меня.
Вы можете подклассифицировать TextInputLayout и использовать это:
package com.mypackage;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.util.AttributeSet;
public class CustomTextInputLayout extends TextInputLayout {
public CustomTextInputLayout(Context context) {
super(context);
}
public CustomTextInputLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomTextInputLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
clearEditTextColorfilter();
}
@Override
public void setError(@Nullable CharSequence error) {
super.setError(error);
clearEditTextColorfilter();
}
private void clearEditTextColorfilter() {
EditText editText = getEditText();
if (editText != null) {
Drawable background = editText.getBackground();
if (background != null) {
background.clearColorFilter();
}
}
}
}
в вашем макете:
<com.mypackage.CustomTextInputLayout
android:id="@+id/register_userUsernameTextLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/register_headerLayout"
android:layout_margin="10dp"
android:textColorHint="#c5c5c5">
<EditText
android:id="@+id/register_userUserNameText"
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="@drawable/selector_bg_edit"
android:hint="نام کاربری"
android:paddingBottom="2dp"
android:textColor="@color/colorAccent"
android:textCursorDrawable="@drawable/bg_input_cursor"
android:textSize="16sp" />
</android.support.design.widget.TextInputLayout>
в моем случае я добавил строку
<solid android: color = "@color/transparent"/>
<shape android:shape="rectangle"
xmlns:android="http://schemas.android.com/apk/res/android" >
<stroke android:color="@color/lightGray" android:width="1dp"/>
<solid android:color="@color/transparent"/>
<padding android:top="7dp" android:bottom="7dp" android:left="7dp" android:right="7dp"/>
<corners android:radius="2dp"/>
</shape>
это приводит к красной границе только не весь фон
Подкласс EditText и примените следующие методы:
Переопределить getBackground и создать Drawable с фоном ввода
@Override
public Drawable getBackground() {
return ContextCompat.getDrawable(getContext(), R.drawable.input_background);
}
ваш Drawable input_brackground может выглядеть следующим образом:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid
android:color="@color/inputBackgroundColor">
</solid>
</shape>
И примените EditText подклассифицированный setBackground после того, как TextInputLayout установил ошибку, например:
private void showTheError(String error){
textInputLayout.setError(error);
editTextSubclassed.setBackgroundColor(getResources().getColor(R.color.inputBackgroundColor));
}
Как и в случае с Шахином Мурсаловым, я вызываю метод init()
в блок-схеме для хранения фона, который можно извлечь, когда создается представление. Кроме того, я уже использовал метод setBackgroundResource()
для сохранения фона и вернул его из getBackground()
:
public class CustomEditText extends EditText{
private Drawable backgroundDrawable;
public EditTextContext context) {
super(context);
this.context = context;
}
public EditTextContext context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
init(attrs);
}
public EditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.context = context;
init(attrs);
}
public void init(AttributeSet attrs){
TypedArray attributes = context.obtainStyledAttributes(attrs, new int[]{android.R.attr.background});
this.backgroundDrawable = attributes.getDrawable(0);
attributes.recycle();
}
@Override
public void setBackgroundResource(@DrawableRes int resId) {
this.backgroundDrawable = ContextCompat.getDrawable(context, resId);
super.setBackgroundResource(resId);
}
@Override
public Drawable getBackground() {
if (backgroundDrawable != null){
return backgroundDrawable;
} else {
return super.getBackground();
}
}
}
Таким образом, я могу указать другой фон в своем макете и изменить его программно.
сначала ваш фон EditText selector_bg_edit должен быть таким
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/code_view_item"
android:state_focused="true"/>
<item android:drawable="@drawable/sign_in_fields"
android:state_focused="false"/>
<item android:drawable="@drawable/sign_in_fields"
android:state_active="false"/>
</selector>
И самое главное, чтобы рисовать, чтобы был прозрачный цвет, как это
<stroke android:width="1dp" android:color="#15A859" />
<solid android:color="#00FFFFFF" />
<corners android:radius="12dp"/>