2017-08-01 78 views
0

請讓我知道我該如何實現這一目標。 我有一個電子郵件編輯文本,如果我沒有輸入任何內容,而不是顯示警報或吐司。 提示將轉換爲紅色。Android在edittext中管理警告消息

如果我輸入了錯誤的電子郵件,則輸入的文本將轉換爲紅色。當我開始再次打字時,它會轉換成黑色。

如果錯誤

  • (沒有進入)暗示紅
  • (當開始進入)提示轉換爲黑白
  • (如果沒有有效的電子郵件地址)輸入的電子郵件轉換爲紅色。
  • (開始重新輸入時)電子郵件文本轉換爲紅色。

感謝

+0

https://stackoverflow.com/a/45158144/3983054 –

回答

0

你需要創建一個自定義的EditText

public class EditTextLight extends EditText { 
    public EditTextLight(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     setTypeface(ApplicationFonts.getLightFont(context)); 
    } 

    @Override 
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { 
     if (getTag() != null) { 
      setTextColor(Color.parseColor(getTag().toString())); 
     } 
    } 

    if (YOUR VALIDATION) 
{edittext.setHint(Validations.setErrorSpanText(edittext.getHint().toString())); 
      } 

public static Spannable setErrorSpanText(String message) { 
     Spannable textToSpan = new SpannableString(message); 
     textToSpan.setSpan(new ForegroundColorSpan(Color.RED), 0, message.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
     return textToSpan; 
    } 

if (edittext.getText().length() == 0) 
        edittext.setHint(Validations.setErrorSpanText(edittext.getHint().toString())); 
       else { 
        edittext.setTextColor(Color.RED); 
       } 
+0

謝謝阿米特,讓我試試看。 –

+0

是的,它的工作原理感謝您的幫助,但我仍然需要改進它,有1個問題。 非常感謝你的朋友 –

0

EditText將這個樣子

<EditText 
    android:id="@+id/email" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_centerInParent="true" 
    android:hint="Enter email here" 
    android:inputType="textEmailAddress" 
    android:textColorHint="@android:color/holo_red_dark" /> 

在你的活動: -

final EditText email = (EditText) findViewById(R.id.email); 
    email.addTextChangedListener(new TextWatcher() 
    { 
     @Override 
     public void beforeTextChanged(CharSequence s, int start, int count, int after) 
     { 
     } 
     @Override 
     public void onTextChanged(CharSequence s, int start, int before, int count) 
     { 
      if (isValidEmail(email.getText().toString().trim())) { 
       email.setTextColor(Color.BLACK); 
      } else 
      { 
       email.setTextColor(Color.RED); 
      } 

     } 
     @Override 
     public void afterTextChanged(Editable s) 
     { 

     } 
    }); 

並添加此功能查看電子郵件驗證: -

public final static boolean isValidEmail(CharSequence target) { 
    if (target == null) { 
     return false; 
    } else { 
     return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches(); 
    } 
} 

需要更多定製,您可以編輯addTextChangedListener和玩它的功能