Tuesday 12 March 2013

Text Watcher Example in Android

activity_main.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="26dp"
            android:layout_marginTop="40dp"
            android:text="Enter Text"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/input_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/textView1"
            android:layout_below="@+id/textView1"
            android:layout_marginTop="22dp"
            android:ems="10"  />

        <TextView
            android:id="@+id/output_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/input_text"
            android:layout_below="@+id/input_text"
            android:layout_marginTop="26dp"
            android:text="Your Text Here"
            android:textAppearance="?android:attr/textAppearanceMedium" />

    </RelativeLayout>



MainActivity.java


package com.rajeshvijayakumar.textwatcher_example;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity implements TextWatcher {

    private EditText mInputText;
    private TextView mOutputText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mInputText = (EditText) findViewById(R.id.input_text);
        mOutputText = (TextView) findViewById(R.id.output_text);
        mInputText.addTextChangedListener(this);
    }

    @Override
    public void afterTextChanged(Editable arg0) {
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence txtWatcherStr, int start, int before, int count) {

        String outputedText = txtWatcherStr.toString();
        mOutputText.setText(outputedText);
    }
}


Output :






Source Code :  Download this Example Here

No comments:

Post a Comment