1 <!-- 2 通过修改<color name="colorAccent">#023cfa</color>可以修改正确提示文本的颜色 3 添加<item name="android:textColorPrimary">@color/textColorPrimary</item>属性可以修改输入文本的颜色 4 --> 5 <android.support.design.widget.TextInputLayout 6 android:id="@+id/text_input_layout" 7 android:layout_width="match_parent" 8 android:layout_height="wrap_content"> 9 10 <EditText 11 android:layout_width="match_parent" 12 android:layout_height="48dp"/> 13 </android.support.design.widget.TextInputLayout>
1 public class MainActivity extends AppCompatActivity { 2 3 private TextInputLayout textInputLayout; 4 5 @Override 6 protected void onCreate(Bundle savedInstanceState) { 7 super.onCreate(savedInstanceState); 8 setContentView(R.layout.activity_main); 9 textInputLayout = (TextInputLayout) findViewById(R.id.text_input_layout); 10 textInputLayout.setHint("请输入邮箱地址"); 11 //获取到TextInputLayout包裹的EditText 12 EditText editText = textInputLayout.getEditText(); 13 editText.addTextChangedListener(new TextWatcher() { 14 @Override 15 public void beforeTextChanged(CharSequence s, int start, int count, int after) { 16 17 } 18 19 @Override 20 public void onTextChanged(CharSequence s, int start, int before, int count) { 21 22 } 23 24 @Override 25 public void afterTextChanged(Editable s) { 26 //如果不包含@认为是非法邮箱地址 27 if (!s.toString().contains("@")) { 28 //允许TextInputLayout显示错误信息 29 textInputLayout.setErrorEnabled(true); 30 //设置错误信息 31 textInputLayout.setError("邮箱地址非法"); 32 } else { 33 textInputLayout.setErrorEnabled(false); 34 } 35 } 36 }); 37 } 38 }