How to customize setError message in Android Studio with Java

Tags: , ,



I have several error messages in an Android Studio app using Java and I cannot figure out how to customize their appearance. I have consulted several answers on this site but none of them have worked for what I want.

This is what the error message looks like.

Error message.

I want to change the colors of the black background, the white text, and the red line and icon.

This is the code for the error message,

String email = editTextEmail.getText().toString().trim();
        String password = editTextPassword.getText().toString().trim();

        if(email.isEmpty()){
            editTextEmail.setError("Please enter an email.");
            editTextEmail.requestFocus();
            return;
        }

and this is the code for the editText object.

<EditText
            android:id="@+id/login_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:gravity="center"
            android:hint="Email"
            android:padding="8dp"
            android:drawableLeft="@drawable/email_icon"
            android:textColor="#417577"
            android:textSize="25dp" />

How do I change the colors displayed in the error message? Also, is there a way to set these color changes for the whole app and not just individually?

Thank you!

Answer

After googling little bit I found some answers for you. Here I am implementing those sites.

  1. devdeeds git repo
  2. findnerd
  3. xspdf

I am implementing that source code which looks like good for me

It is easy way to change color. If you have idea of html than you might see here you are just changing color by html format.

editText.setError(Html.fromHtml("<font color="#000000">"error!"</font>"));

Following source code used in java

int errorColor;
    final int version = Build.VERSION.SDK_INT;
    if (version >= 23) {

         errorColor = ContextCompat.getColor(getApplicationContext(), R.color.errorColor);
    } else {
         errorColor = getResources().getColor(R.color.errorColor);
    }


    String errorString = "This field cannot be empty";  // your error message
    ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(errorColor);
    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(errorString);
    spannableStringBuilder.setSpan(foregroundColorSpan, 0, errorString.length(), 0);
    editTextView.setError(spannableStringBuilder);


Source: stackoverflow