Monday, June 25, 2012

Android TextWatcher Example



main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText 
        android:id="@+id/entry"
        android:layout_marginTop="10dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
<TextView 
        android:id="@+id/txtview1"
        android:layout_width="fill_parent"
        android:textSize="25.0dp"
        android:gravity="center"
        android:layout_height="wrap_content"
        android:text="TextWatcher" />
</LinearLayout>


MaxLengthWatcher.java:
public class MaxLengthWatcher implements TextWatcher {  
  
    private int maxLen = 0;  
    private EditText editText = null;  
      
      
    public MaxLengthWatcher(int maxLen, EditText editText) {  
        this.maxLen = maxLen;  
        this.editText = editText;  
    }  
  
    public void afterTextChanged(Editable arg0) {  
        // TODO Auto-generated method stub  
          
    }  
  
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,  
            int arg3) {  
        // TODO Auto-generated method stub  
          
    }  
  
    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {  
        // TODO Auto-generated method stub  
        Editable editable = editText.getText();  
        int len = editable.length();  
          
        if(len > maxLen)  
        {  
            int selEndIndex = Selection.getSelectionEnd(editable);  
            String str = editable.toString();  
            //Interception of a new string 
            String newStr = str.substring(0,maxLen);  
            editText.setText(newStr);  
            editable = editText.getText();           
            int newLen = editable.length();  
            if(selEndIndex > newLen)  
            {  
                selEndIndex = editable.length();  
            }  
            //Set the new cursor position 
            Selection.setSelection(editable, selEndIndex);  
              
        }  
    }  
}


TextWatcherActivity.java :
public class TextWatcherActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        EditText editText = (EditText) findViewById(R.id.entry);  
        editText.addTextChangedListener(new MaxLengthWatcher(10, editText));  
    }
}


Download Source Code: AndroidTextWatcher









0 comments:

Post a Comment

 
Powered by Blogger