Monday, 10 June 2013

Today I'm going to post one of the different kind of post that I think can help other newbie Android developers too!

    In my recent project my requirement was, to create Edit Text field with specific format as when user types characters in edit text then after five digts a hiphen sign should be added automatically and again after 7 digits a hiphen sign should be added automatically like this:

 5 digits [hiphen] 7 digits [hiphen]1 digit      (12345-6789101-1).

So it was not an easy and common task, but i think many other newbie developers feels difficulty to handle these kind of task.that's why i am posting this small tutorial on Edit text format.

Set Edit text in your Layout File:


<EditText
android:id="@+id/etNICNO_Sender"
android:layout_marginLeft="35dp"
android:layout_marginTop="10dp"
android:hint="00000-0000000-0"
android:maxLength="15" />

EditText will show the hint like this:
   
EditText with the format of nic(pk).
So to achieve this, we should know that what is TextWatcher (When an object of a type is attached to an Editable, its methods will be called when the text is changed ).Means when user type, enter or deletes text in EditText the text watcher will track the every entered or deleted character in the Edit Text Field. 

The TextWatcher Class has Three Methods:

1. afterTextChanged(Editable s):

    This method is called to notify you that, somewhere within s, the text has been changed. It is legitimate to make further changes to s from this callback, but be careful not to get yourself into an infinite loop, because any changes you make will cause this method to be called again recursively. (You are not told where the change took place because other afterTextChanged() methods may already have made other changes and invalidated the offsets. But if you need to know here, you can use setSpan(Object, int, int, int) in onTextChanged(CharSequence, int, int, int) to mark your place and then look up from here where the span ended up.

2. beforeTextChanged (CharSequence s, int start, int count, int after):

        This method is called to notify you that, within s, the count characters beginning at start are about to be replaced by new text with length after. It is an error to attempt to make changes to s from this callback.

3. onTextChanged(CharSequence s, int start, int before, int count):

      This method is called to notify you that, within s, the count characters beginning at start have just replaced old text that had length before. It is an error to attempt to make changes to s from this callback.

So now I think we are ready to know that how can we implement this to solve our problem to format the input.

In Activity's onCreate() :

in Activity's onCreate get the reference of EditText that you have already defined in layout and addTextChangedListner by passing the TextWatcher Class (discussed above).

      //get the reference of this edit text field
        EditText  etNICNO_Sender=(EditText)findViewById(R.id.etNICNO_Sender);
        /*add textChangeListner with TextWatcher argument
               by adding text change listner with text watcher we can get three methods of
               Edit Text 1) onTextChanged 2) beforeTextChanged 3) afterTextChanged
               these methods work when user types in text feild.
         */
        etNICNO_Sender.addTextChangedListener(new TextWatcher() {
         int len=0;
         @Override
         public void onTextChanged(CharSequence s, int start, int before, int count) {
          // TODO Auto-generated method stub

          String str = etNICNO_Sender.getText().toString();

          if((str.length()==5 && len <str.length()) || (str.length()==13 && len <str.length())){
           //checking length  for backspace.
           etNICNO_Sender.append("-");
           //Toast.makeText(getBaseContext(), "add minus", Toast.LENGTH_SHORT).show();
          }
         }
         @Override
         public void beforeTextChanged(CharSequence s, int start, int count,
           int after) {
          // TODO Auto-generated method stub
          String str = etNICNO_Sender.getText().toString();
          len = str.length();
         }
         @Override
         public void afterTextChanged(Editable s) {
          // TODO Auto-generated method stub

         }
        });

So this was short tutorial on setting Custom Text Format for editText.Hope you guyz enjoyed to learn this small tutorial on Text Format.Wasn't that so simple? enjoy guyz! and do let me know your ideas about this post.
   

Cheers
Hamad Shaikh