Material Design Textinputlayout Use example

Source: Internet
Author: User
Tags valid email address

Using Textinputlayout to create a login interface introduction

Google in the 2015 IO Conference, brought us more detailed material design specifications, but also brought us a new Android design support Library, in this support repository, Google provides us with a more standard MD design-style control. Most importantly, the Android Design Support Library is more compatible and can be directly backwards compatible to Android 2.2. It has to be said to be a conscience.

  • Using Textinputlayout
  • Create a new project
    In Android Studio, from the File menu, choose New > New Project, fill in the necessary information configuration, and create the project. API 7 is used in my example, which is the lowest level supported by the Design support library. This setting allows your device to run as much as possible on more devices, and I have MainActivity changed the LoginActivity layout file activity_login.xml .
    After the project setup number, remove the auto-generated onCreateOptionsMenu() and onOptionsItemSelected () delete the corresponding XML under Res/menu (because the menu is not available).
  • Import Support Libraries
    Using the Textinputlayout control requires importing two libraries, one is appcompat-v7, ensuring material styles can be backwards compatible. The other is the design support Library.
    In the project's Build.gradle file, add the following dependencies (dependencies):

        dependencies {        compile fileTree(dir: ‘libs‘, include: [‘*.jar‘])        compile ‘com.android.support:design:22.2.0‘        compile ‘com.android.support:appcompat-v7:22.2.0‘    }

    If Gralde does not automatically require a sync (synchronize) project, select or press from the build menu so that as Make module ‘app‘ F9 will automatically acquire the necessary resources.

  • Design UI
    The UI is simple, a welcome tag (can be easily replaced later into a picture) and two edittext (username, password box), not centered plus a login button. Then choose a beautiful back color.
    Another detail to note is the inputtype of two input boxes, the first box set to Textemail, the second box set to Textpassword, and the layout as shown below.

    <linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:background=" #e3e3e3 "android:layout_width=" Match_parent "android:layout_height = "Match_parent" android:padding= "@dimen/activity_horizontal_margin" tools:context= ". Loginactivity "android:orientation=" vertical "> <relativelayout android:layout_width=" match_parent "Android oid:layout_height= "wrap_content" android:layout_weight= "0.5" android:orientation= "vertical" > <t Extview android:layout_width= "match_parent" android:layout_height= "Wrap_content" android:layout_cent             Erinparent= "true" android:gravity= "center" android:text= "Welcome" android:textsize= "30SP" Android:textcolor= "#333333" ></textview> </relativelayout> </linearlayout><linear Layout android:layout_width= "match_parent" android:layout_height= "Wrap_cOntent "android:layout_weight=" 0.5 "android:orientation=" vertical "> <edittext android:id=" @+id/ Username "android:layout_width=" match_parent "android:layout_height=" Wrap_content "Androi D:inputtype= "textemailaddress" ></edittext> <edittext android:id= "@+id/password" Android: Layout_width= "Match_parent" android:layout_height= "wrap_content" android:inputtype= "TextPass Word "></edittext> <button android:id=" @+id/btn "android:layout_margintop=" 4DP "an Droid:layout_width= "Match_parent" android:layout_height= "wrap_content" android:text= "Login" ></ Button> </linearlayout>

You may also want to get rid of the app bar (app bar), which is the action bar you've previously said, and modify the Style.xml.

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"></style>
    • Using Textinputlayout
      Finally to the most interesting part of the tutorial, the Textinputlayout control behaves just like LinearLayout, which is a container. Only one child element can be placed in the textinputlayout, and the ScrollView is somewhat similar, and the child element must be edittext.

      <android .support.design.widget.TextInputLayout    android:id="@+id/usernameWrapper"    android:layout_width="match_parent"    android:layout_height="wrap_content">    <edittext android:id="@+id/username"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:inputType="textEmailAddress"        android:hint="Username"></edittext></android>

Did you notice that I set an attribute-hint in EditText. This property is very familiar to everyone, EditText did not enter the time, hint will show, when the first letter entered the time, hint disappeared. The experience is not so good.
Thanks to Textinputlayout, this is not a problem right now. When you enter the first letter in the EditText to hide the hint, a floating label appears in Textinputlayout to show the hint and is responsible for a cool material animation.
Below, we give password also to one.

<android .support.design.widget.TextInputLayout    android:id="@+id/passwordWrapper"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:layout_below="@id/usernameWrapper"    android:layout_marginTop="4dp">    <edittext android:id="@+id/password"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:inputType="textPassword"        android:hint="Password"></edittext></android>

If you run the program now, what effect is wood there. Of course, EditText's hint effect is excluded. Spicy, why can the wood have animation pinch? We're missing a bit of code.
-Set prompt (hints)
In the setContentView() following, initialize the Textinputlayout reference.

final TextInputLayout usernameWrapper = (TextInputLayout) findViewById(R.id.usernameWrapper);final TextInputLayout passwordWrapper = (TextInputLayout) findViewById(R.id.passwordWrapper);

To see hint floating animations, you also need to call thesetHint

usernameWrapper.setHint("Username");passwordWrapper.setHint("Password");

After this, the application has been fully compliant with material design, running the program, and then you will see the login screen.

Handling Errors

Textinputlayout Another great feature is the ability to handle error conditions. By validating user input, you can prevent users from entering the wrong mailbox or entering a password that does not conform to the rule.
Some input validation, validation is done in the background, resulting in errors will be fed back to the foreground, and finally presented to the user. Very time consuming and poor user experience. The best way to do this is to check the back of the request.

  • Implements the OnClick method
    handles Click events First, there are many ways to handle click events, you set the method name in XML, and then the activity improves the method. or Setonclicklistener. The guy who wrote the article liked the back.

      Btn.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {// (STUB}});  

    In fact, when this method is called, the keyboard is not needed. Unfortunately, Android is not automatically hidden. What do we do? Call the following method.

      private void Hidekeyboard () {View view = Getcurrentfocus ();            if (view! = null) {((Inputmethodmanager) Getsystemservice (Context.input_method_service)).    Hidesoftinputfromwindow (View.getwindowtoken (), inputmethodmanager.hide_not_always); }}
  • Validating user input
    before setting the error label, let's make it clear what the error is and what is not. We assume that the user name verifies that the mailbox is correct.
    Verifying the mailbox is a little bit more complicated, we can do it with Apache Commons Library. I use a regular expression in Wikipedia.

     /^[a-za-z0-9#_~!$& ' () *+,;=:. " (),:; <>@\[\]\\][email protected][a-za-z0-9-]+ (\.[ a-za-z0-9-]+) *$/ 

    Why do you write so, you don't explain ...
    Since we want to validate a string, we have to rely on the pattern and Matcher, which are below Java.util.regex. Import them in the activity.

      private static final String Email_pattern = "^[a-za-z0-9#_~!$& ' () *+,;=:.\" (),:; <>@\\[\\]\\\ \][email protected][a-za-z0-9-]+ (\\.[ a-za-z0-9-]+) *$ ";p rivate pattern pattern = pattern.compile (email_pattern);p rivate Matcher Matcher;public Boolean    Validateemail (String email) {matcher = pattern.matcher (email); return matcher.matches ();}  

    Password validation is relatively straightforward and different organizations have different authentication methods. But most have a minimum length limit. The most reasonable rule is to enter at least six characters.

      public boolean validatepassword (String password) {return password.length () > 5}  
  • Receive data
    As has been said before, Textinputlayout is just a container. Unlike LinearLayout and ScrollView, you can directly get its child elements through a specific method (Getedittext). Basic wood is necessary to use Findviewbyid.
    If no edittext,getedittext in Textinputlayout will return NULL, you have to pay attention to the NPE.

    public void onClick(View v) {    hideKeyboard();    String username = usernameWrapper.getEditText().getText().toString();    String password = usernameWrapper.getEditText().getText().toString();    // TODO: Checks    // TODO: Login}
  • Display Error
    Textinputlayout error handling is simple and fast. The relevant methods have setErrorEnabled and setError .
    SetError will pop up a red hint message that appears under EditText, and if the incoming error message is NULL, the previous message is erased. This method also turns the EditText red.
    Seterrorenabled is the control of this function. This directly affects the size of the layout. Please do your own brain repair ....
    It is also important to note that if seterrorenabled (true) is not called but the SetError method is called and a non-empty message is passed in, seterrorenabled (true) is automatically called.

Correct and error conditions we have explained, the following implementation of the OnClick method.

public void onClick(View v) {    hideKeyboard();     String username = usernameWrapper.getEditText().getText().toString();    String password = usernameWrapper.getEditText().getText().toString();    if (!validateEmail(username)) {        usernameWrapper.setError("Not a valid email address!");    } else if (!validatePassword(password)) {        passwordWrapper.setError("Not a valid password!");    } else {        usernameWrapper.setErrorEnabled(false);        passwordWrapper.setErrorEnabled(false);        doLogin();    }}

The following is an empty logon method:

public void doLogin() {    Toast.makeText(getApplicationContext(), "OK! I‘m performing login.", Toast.LENGTH_SHORT).show();    // TODO: login procedure; not within the scope of this tutorial.}
    • Modify Textinputlayout Background

      <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">    <item name="colorAccent">#3498db</item></style>

Summarize

Thank you for the design support library that brought us textinputlayout.

The following do not want to translate, good study, day up.

The design paradigm that this widget implements allows users to never never lose context of the information they is enter ing and it is actually introduced by the last year of Google, along with Material Design.

At that time, there is no support library giving developers the possibility to put this widget into action in their Proje CTS, until Google I/O 2015. Now, if your application expects some sort of data input, you'll finally be truly material design compliant.

Material Design Textinputlayout Use example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.