TextInputLayout是android.support.design.widget裏的一個控件,須要配合EditText一塊兒使用才行,並且必須是包裹住EditText,例如:android
<android.support.design.widget.TextInputLayout android:layout_height="wrap_content" app:hintTextAppearance="@style/hintStyle" android:layout_width="match_parent"> <EditText android:layout_width="match_parent" android:layout_height="@dimen/height_150dp" android:layout_margin="@dimen/margin_5dp" android:gravity="top" android:hint="設置輸入內容" android:maxLength="120" android:layout_gravity="center_horizontal|top" android:background="@null" android:textColor="@color/light_grey"/> </android.support.design.widget.TextInputLayout>
TextInputLayout是爲了檢測輸入的合法性應運而生的新控件,咱們在平常項目中經常須要檢測用戶輸入字符是否符合要求,必須合法性檢查或者字符數目檢查,TextInputLayout能夠讓提示變得靈活和醒目.好比咱們如今就構造一個輸入合法手機號的EditText的代碼.app
``` public class MainActivity extends AppCompatActivity { @Bind(R.id.et) EditText et; @Bind(R.id.et_input_layout) TextInputLayout etInputLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); et.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } //TextInputLayout的setError方法必須放到onTextChanged裏 @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (isMobileNum(s.toString())){ Log.e("輸入的是合法的字符串","輸入的是合法的字符串"); etInputLayout.setErrorEnabled(false); }else{ Toast.makeText(MainActivity.this,"輸入的不是合法的字符串,並讓字符串歸空",Toast.LENGTH_SHORT).show(); //啓動錯誤提示 etInputLayout.setErrorEnabled(true); etInputLayout.setError("輸入的不是手機號"); } isMobileNum(s.toString()); } //當咱們有須要判斷輸入字符內容長度的要求時,放到afterTextChanged方法裏 @Override public void afterTextChanged(Editable s) { //判斷輸入內容的長度放在此處 } }); } public static boolean isMobileNum(String mobiles) { Pattern p = Pattern .compile("^((13[0-9])|(15[^4,//D])|(18[0,5-9]))//d{8}$"); Matcher m = p.matcher(mobiles); return m.matches(); }
}ide