标签:
这两个控件也是Google在2015 I/O大会上公布的Design Library包下的控件,使用比較简单,就放在一起讲了,但有的地方也是须要特别注意一下。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:id="@+id/textInput_layout_name"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="user_name" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/textInput_layout_password"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="user_password" />
</android.support.design.widget.TextInputLayout>
</LinearLayout>在代码中实现: TextInputLayout mTextInputLayoutName = (TextInputLayout) findViewById(R.id.textInput_layout_name);
TextInputLayout mTextInputLayoutPassword = (TextInputLayout) findViewById(R.id.textInput_layout_password);
//mTextInputLayoutName.getEditText()返回的是它的子EditText控件,一个TextInputLayout仅仅能包括一个EditText控件
mTextInputLayoutName.getEditText().addTextChangedListener(new MyTextWatcher(mTextInputLayoutName, "username长度不能小于6位"));
mTextInputLayoutPassword.getEditText().addTextChangedListener(new MyTextWatcher(mTextInputLayoutPassword, "密码长度不能小于6位"));MyTextWatcher代码:class MyTextWatcher implements TextWatcher {
private TextInputLayout mTextInputLayout;
private String errorInfo;
public MyTextWatcher(TextInputLayout textInputLayout, String errorInfo) {
this.mTextInputLayout = textInputLayout;
this.errorInfo = errorInfo;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (mTextInputLayout.getEditText().getText().toString().length() < 6) {
mTextInputLayout.setErrorEnabled(true);//是否设置错误提示信息
mTextInputLayout.setError(errorInfo);//设置错误提示信息
} else {
mTextInputLayout.setErrorEnabled(false);//不设置错误提示信息
}
}
}最值得注意的一点就是Snackbar不能同一时候显示多个,仅仅能一次显示一个。而Toast能够同一时候显示多个这和Toast不同。
Snackbar.make(rootView, "This is a SnackBar", Snackbar.LENGTH_SHORT).show();//第一个參数是SnackBar显示在哪个视图上,必须设置,不能为null,一个界面也不能同一时候显示两个SnackBar当中特别须要注意第一个參数。它表示Snackbar是显示在哪个视图上,不可为null,比方我们能够通过页面中其他的view.getRootView()得到根视图,再把rooView设置进去就可以。
//带button的SnackBar
Snackbar.make(rootView,"带button的SnackBar",Snackbar.LENGTH_SHORT).setAction("UNDO", new View.OnClickListener() {
@Override
public void onClick(View v) {
//do something ...
}
}).show();Material Design之TextInputLayout、Snackbar的使用
标签:
原文地址:http://www.cnblogs.com/bhlsheji/p/5349056.html