好长时间没有上知乎了,今天打开的时候,发现提示令牌失效了,让重新登陆,一看这个效果,其实很好实现的,在Material Design里面其实有相关的view的,为TextInputLayout,这里简单写个demo:
xml布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".MainActivity"
android:orientation="vertical"
tools:showIn="@layout/activity_main">
<android.support.design.widget.TextInputLayout
android:id="@+id/til_id"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/til_id2"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.TextInputLayout>
</LinearLayout>
接下来,我们就在Activity里面去实现相关的处理
public class MainActivity extends AppCompatActivity {
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextInputLayout textInputLayout1 = (TextInputLayout) findViewById(R.id.til_id);
final TextInputLayout textInputLayout2 = (TextInputLayout) findViewById(R.id.til_id2);
generateEdit(textInputLayout1, "用户名", "用户名输入不要超过5位",5);
generateEdit(textInputLayout2,"密码","密码长度应小于10位",10);
}
private void generateEdit(final TextInputLayout text,String textinput, final String texterror, final int length) {
editText = text.getEditText();
text.setHint(textinput);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (s.length() > length) {
text.setError(texterror);
text.setErrorEnabled(true);
} else {
text.setErrorEnabled(false);
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
}
最终的效果如下: