SMS character counter for an edit text

To create a SMS character counter for an edittext text in your app, all you need is a Text Watcher. Text Watcher which listens to the change in text in the edit text. Through it you can listen to three events, they are: beforeTextChanged, onTextChanged, afterTextChanged. In this process we listen to onTextChanged. Here is the whole code you need to create the character counter:

 public class MainActivity extends ActionBarActivity {  
      int textLeft;  
      int smsNo = 1;  
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.activity_main);  
           final TextView counter = (TextView) findViewById(R.id.textView1);  
           EditText edittext = (EditText) findViewById(R.id.edit_text1);  
           final TextWatcher watcher = new TextWatcher() {  
                public void beforeTextChanged(CharSequence s, int start, int count,  
                          int after) {  
                }  
                public void onTextChanged(CharSequence s, int start, int before,  
                          int count) {  
                     int sms = s.length() / 160;  
                     float d = (float) s.length() / 160;  
                     double textLeftt = 160 * (1 - (d - sms));  
                     textLeft = (int) Math.round(textLeftt);  
                     smsNo = sms + 1;  
                     counter.setText(textLeft + "/160 (" + smsNo + ")");  
                }  
                public void afterTextChanged(Editable s) {  
                }  
           };  
           edittext.addTextChangedListener(watcher);  
      }  
 } 

Here, SMS is the no of sms text messages, 160 is the standard no of characters an sms messages has. Emojis occupy two characters in an SMS message.

Comments


  1. Your very own commitment to getting the message throughout came to be rather powerful and have consistently enabled employees just like me to arrive at their desired goals.
    Matlab Training in Chennai | Best Matlab Training in Chennai
    AWS Training in Chennai | Best AWS Training in Chennai
    Devops Training in Chennai | Best Devops Training in Chennai

    ReplyDelete
  2. Hello, I read your blog occasionally, and I own a similar one, and I was just wondering if you get a lot of spam remarks? If so how do you stop it, any plugin or anything you can advise? I get so much lately it’s driving me insane, so any assistance is very much appreciated.
    AWS Training in Chennai | Best AWS Training in Chennai
    Best Data Science Training in Chennai
    Best Python Training in Chennai
    Best RPA Training in Chennai
    Digital Marketing Training in Chennai
    Matlab Training in Chennai
    <

    ReplyDelete

Post a Comment