auto Clear View from EditText - Android User Interface

Android examples for User Interface:EditText

Description

auto Clear View from EditText

Demo Code


//package com.java2s;

import android.text.Editable;

import android.text.TextUtils;
import android.text.TextWatcher;

import android.view.View;
import android.widget.EditText;

public class Main {

    public static void autoClear(final EditText editText,
            final View clearView) {
        if (null != editText && null != clearView) {
            editText.addTextChangedListener(new TextWatcher() {
                @Override// w ww  .  j av  a 2  s . c  om
                public void beforeTextChanged(CharSequence s, int start,
                        int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start,
                        int before, int count) {
                    clearView.setVisibility(TextUtils.isEmpty(s) ? View.GONE
                            : View.VISIBLE);
                }

                @Override
                public void afterTextChanged(Editable s) {
                }
            });
            editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    clearView.setVisibility(!TextUtils.isEmpty(editText
                            .getText().toString()) && hasFocus ? View.VISIBLE
                            : View.GONE);
                }
            });
            clearView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    editText.setText("");
                }
            });
        }
    }

    public static void setText(EditText editText, String text) {
        if (null != editText && !TextUtils.isEmpty(text)) {
            editText.setText(text);
            editText.setSelection(text.length());
        }
    }
}

Related Tutorials