Android TextWatcher Example
Lets us jump straight into the TextWatcher example in android. In this tutorial, we will create a simple EditField for entering password, and the text watcher will show the same password in another TextView.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:padding="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingBottom="10dp" android:text="Enter your password and see the magic!!" android:textAppearance="?android:attr/textAppearanceLarge" android:textStyle="bold" /> <EditText android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Password" android:inputType="textPassword" android:padding="12dp"> <requestFocus /> </EditText> <TextView android:id="@+id/passwordHint" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/password" android:background="#ffd33a26" android:padding="5dp" android:text="* Not Entered" android:textColor="#fff" /> </LinearLayout>
Using TextWatcher in Activity
import android.app.Activity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends Activity { private EditText passwordEditText; private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /* Initializing views */ passwordEditText = (EditText) findViewById(R.id.password); textView = (TextView) findViewById(R.id.passwordHint); textView.setVisibility(View.GONE); /* Set Text Watcher listener */ passwordEditText.addTextChangedListener(passwordWatcher); } private final TextWatcher passwordWatcher = new TextWatcher() { public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { textView.setVisibility(View.VISIBLE); } public void afterTextChanged(Editable s) { if (s.length() == 0) { textView.setVisibility(View.GONE); } else{ textView.setText("You have entered : " + passwordEditText.getText()); } } }; }

No comments:
Post a Comment