Thursday, June 28, 2012

Android EditText TextWatcher Example

Android EditText TextWatcher Example
 TextWatcher
This methods  will be called when the text is changed.
Text Watcher Having Three Events.
1.beforeTextChanged
2.onTextChanged
3.afterTextChanged
  beforeTextChanged   This means that the characters are about to be replaced with some new text. The text        is  uneditable.   Use: when you need to take a look at the old text which is about to change.
 onTextChanged Changes have been made, some characters have just been replaced. The text is uneditable.Use: when you need to see which characters in the text are new.
 afterTextChanged The same as above, except now the text is editable.
    Use: when a you need to see and possibly edit new text.

Problem
EditText maxLength:100 

Ex: when you type the text  in EditText you can see remaining length using TextWatcher.
Solution :

Activity Code 
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
public class AndroidQAActivity extends Activity implements TextWatcher {
EditText text;
int textCount;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (EditText)findViewById(R.id.url_field);
text.addTextChangedListener(this);
}
/* TextWatcher Implementation Methods */
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int end) {
textCount = text.getText().length();
setTitle("Message :: "+String.valueOf(textCount)+"/100");
}
public void afterTextChanged(Editable s) {
}
}

Screen Shot:


XMl Code 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/url_field"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:maxLength="100"
android:lines="1" />
</LinearLayout>


Check out this may be help you

Related Posts Plugin for WordPress, Blogger...