Как изменить цвет TextInputLayout в Android?

Привет, я новичок в Android, и в своем приложении я использую поля TextInputLayout.

Я установил цвет границы EditText и не хочу устанавливать цвет фона текста редактирования, но в соответствии с моим кодом ниже, когда я нажимаю кнопку «ЗАРЕГИСТРИРОВАТЬСЯ», цвет фона текста редактирования отображается красным.

Как мы можем изменить этот цвет фона?

edittext_background:-

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="@android:color/white" />

    <stroke
        android:width="1dip"
        android:color="@android:color/holo_purple" />

    <padding android:left="5dp"
        android:top="5dp"
        android:right="5dp"
        android:bottom="5dp"/>

</shape>

стили:-

 <style name="TextAppearance.App.TextInputLayout" parent="@android:style/TextAppearance">
        <item name="android:textColor">@color/splahbgcolor</item>
        <item name="android:textSize">14sp</item>
    </style>

основной.xml: -

<LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="?attr/actionBarSize"
        android:orientation="vertical"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:paddingTop="60dp">

        <android.support.design.widget.TextInputLayout
            android:id="@+id/input_layout_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:hintTextAppearance="@style/TextAppearance.App.TextInputLayout">

            <android.support.v7.widget.AppCompatEditText
                android:id="@+id/input_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:background="@drawable/edittext_background"
                android:ems="10"
                android:inputType="textEmailAddress"
                android:padding="8dp"
                android:textColor="@color/splahbgcolor"
                android:hint="@string/hint_name" />

        </android.support.design.widget.TextInputLayout>

Основная деятельность:-

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private EditText inputName, inputEmail, inputPassword;
    private TextInputLayout inputLayoutName, inputLayoutEmail, inputLayoutPassword;
    private Button btnSignUp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        inputLayoutName = (TextInputLayout) findViewById(R.id.input_layout_name);
        inputLayoutEmail = (TextInputLayout) findViewById(R.id.input_layout_email);
        inputLayoutPassword = (TextInputLayout) findViewById(R.id.input_layout_password);

        inputName = (EditText) findViewById(R.id.input_name);
        inputEmail = (EditText) findViewById(R.id.input_email);
        inputPassword = (EditText) findViewById(R.id.input_password);

        btnSignUp = (Button) findViewById(R.id.btn_signup);

        inputName.addTextChangedListener(new MyTextWatcher(inputName));
        inputEmail.addTextChangedListener(new MyTextWatcher(inputEmail));
        inputPassword.addTextChangedListener(new MyTextWatcher(inputPassword));

        btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                submitForm();
            }
        });
    }

    /**
     * Validating form
     */
    private void submitForm() {

        if (!validateName()) {
            return;
        }

        if (!validateEmail()) {
            return;
        }

        if (!validatePassword()) {
            return;
        }

        Toast.makeText(getApplicationContext(), "Thank You!", Toast.LENGTH_SHORT).show();
    }

    private boolean validateName() {

        if (inputName.getText().toString().trim().isEmpty()) {
            inputLayoutName.setError(getString(R.string.err_msg_name));
            requestFocus(inputName);
            return false;

        } else {
            inputLayoutName.setErrorEnabled(false);
        }

        return true;
    }

    private boolean validateEmail() {

        String email = inputEmail.getText().toString().trim();

        if (email.isEmpty() || !isValidEmail(email)) {
            inputLayoutEmail.setError(getString(R.string.err_msg_email));
            requestFocus(inputEmail);
            return false;
        } else {
            inputLayoutEmail.setErrorEnabled(false);
        }

        return true;
    }

    private boolean validatePassword() {

        if (inputPassword.getText().toString().trim().isEmpty()) {
            inputLayoutPassword.setError(getString(R.string.err_msg_password));
            requestFocus(inputPassword);
            return false;
        } else {
            inputLayoutPassword.setErrorEnabled(false);
        }

        return true;
    }

    private static boolean isValidEmail(String email) {

        return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }

    private void requestFocus(View view) {

        if (view.requestFocus()) {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }

    private class MyTextWatcher implements TextWatcher {

        private View view;

        private MyTextWatcher(View view) {
            this.view = view;
        }

        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        public void afterTextChanged(Editable editable) {

            switch (view.getId()) {

                case R.id.input_name:
                    validateName();
                    break;

                case R.id.input_email:
                    validateEmail();
                    break;

                case R.id.input_password:
                    validatePassword();
                    break;
            }
        }
    }
}

введите здесь описание изображения


person Krish    schedule 21.06.2016    source источник
comment
изменить цвет акцента   -  person SaravInfern    schedule 21.06.2016
comment
Каково значение цвета splahbgcolor.??   -  person Harshad Pansuriya    schedule 21.06.2016
comment
где я могу изменить я не понимаю   -  person Krish    schedule 21.06.2016
comment
это мой цвет заставки ===>EF4836   -  person Krish    schedule 21.06.2016
comment
Вы можете опубликовать код Onclick из Button.   -  person Harshad Pansuriya    schedule 21.06.2016
comment
Могу ли я поделиться с вами своим типовым проектом?   -  person Krish    schedule 21.06.2016
comment
очень маленький, тогда вы можете легко найти мою ошибку   -  person Krish    schedule 21.06.2016
comment
да я написал см. один раз   -  person Krish    schedule 21.06.2016
comment
@Krish Ошибка отображается в поле, потому что вы меняете размер поля. На самом деле есть только строка для EditText, но у вас есть поле для создания, поэтому это относится ко всему окну.   -  person Harshad Pansuriya    schedule 21.06.2016
comment
тогда как я могу изменить это?   -  person Krish    schedule 21.06.2016


Ответы (2)


использовать тему вместо hintTextAppearance

 <android.support.design.widget.TextInputLayout
            android:id="@+id/input_layout_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
           app:hintTextAppearance="@color/colorPrimary"
            android:theme="@style/TextAppearance>

твой стиль

 <style name="TextAppearance" parent="@android:style/TextAppearance">
        <item name="android:textColor">@color/splahbgcolor</item>
        <item name="android:textColorHint">@color/splahbgcolor</item>
    </style>
person KDeogharkar    schedule 21.06.2016
comment
я получаю исключение - person Krish; 21.06.2016
comment
НЕИСПРАВНОЕ ИСКЛЮЧЕНИЕ: основной java.lang.UnsupportedOperationException: невозможно преобразовать в цвет: тип = 0x2 - person Krish; 21.06.2016
comment
не могли бы вы изменить имя своего стиля, например, для TextAppearance.App.TextInputLayout, на style_textlayout и проверьте @Krish - person KDeogharkar; 21.06.2016
comment
Вы имеете в виду ‹имя стиля=style_textlayout parent=@android:style/TextAppearance›? - person Krish; 21.06.2016
comment
Давайте продолжим это обсуждение в чате. - person Krish; 21.06.2016
comment
Я обновляю свой ответ. - person KDeogharkar; 21.06.2016

Версия TL;DR:
Звоните inputName.setBackgroundResource(R.drawable.edittext_background);после каждого звонка inputLayoutName.setError(getString(R.string.err_msg_name));

Более длинная версия:
Это происходит потому, что когда вы вызываете setError(errormsg) в TextInputlayout внутренне (в коде TextInputLayout), этот метод после настройки Errorview вызывает следующий метод:< бр> updateEditTextBackground();

Внутри метода updateEditTextBackground() класса TextInputLayout цвет фона вашего editText изменяется с помощью следующей строки:

if (mErrorShown && mErrorView != null) {
        // Set a color filter of the error color
        editTextBackground.setColorFilter(
                AppCompatDrawableManager.getPorterDuffColorFilter(
                        mErrorView.getCurrentTextColor(), PorterDuff.Mode.SRC_IN));
    }

В результате цвет фона вашего Edittext изменится на красный цвет (это взято из Errorview's стиля textAppearance по умолчанию из фреймворка).

Единственным возможным обходным путем в вашем случае было бы добавить строку ниже после всех ваших методов setError в предложении if:

inputName.setBackgroundResource(R.drawable.edittext_background);

validateName() метод:

   private boolean validateName() {

    if (inputName.getText().toString().trim().isEmpty()) {
        inputLayoutName.setError(getString(R.string.err_msg_name));
        inputName.setBackgroundResource(R.drawable.edittext_background);
        requestFocus(inputName);
        return false;

    } else {
        inputLayoutName.setErrorEnabled(false);
    }

    return true;
}

Возможно, это единственный обходной путь для вашей проблемы на данный момент.
Не уверен, что это подходящий способ справиться с пользовательской фоновой ситуацией Edittext.

person PunitD    schedule 22.06.2016