TextInputLayout輸入框驗證
阿新 • • 發佈:2018-02-16
int utl void rri bubuko log creat alt hint
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 3private 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 }
TextInputLayout輸入框驗證