The EditText is the standard text entry widget in Android apps. If the user needs to enter text into an app, this is the primary way for them to do that. Traditionally, the EditText hides the hint message after the user starts typing. In addition, any validation error messages had to be managed manually by the developer.
Starting with Android M and the design support library, the TextInputLayout can be used to setup a floating label to display hints and error messages. First, wrap the EditText in a TextInputLayout:
<android.support.design.widget.TextInputLayout android:id="@+id/username_text_input_layout" android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:id="@+id/etUsername" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:ems="10" android:hint="Username" /> </android.support.design.widget.TextInputLayout>
We can also use the TextInputLayout to display error messages using the setError and setErrorEnabled properties in the activity at runtime:
private void setupFloatingLabelError() { final TextInputLayout floatingUsernameLabel =
(TextInputLayout) findViewById(R.id.username_text_input_layout); floatingUsernameLabel.getEditText().addTextChangedListener(new TextWatcher() { // ... @Override public void onTextChanged(CharSequence text, int start, int count, int after) { if (text.length() > 0 && text.length() <= 4) { floatingUsernameLabel.setError(getString(R.string.username_required)); floatingUsernameLabel.setErrorEnabled(true); } else { floatingUsernameLabel.setErrorEnabled(false); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { } }); }
Here we use the addTextChangedListener to watch as the value changes to determine when to display the error message or revert to the hint.
Mostofak029@gmail.com
ReplyDelete