How to create EditText view with clear Text Button

Custom EditText View


How to create custom Editing text view that includes "X" button for clearing entered text.

In this tutorial we are going learn how to make custome edit text view which containt "X" clear button and how to clear all the text from edit text view when "X" clear button is click.

I am extending EditText view class in my  CustomeEditTextWithClearButton class, so that we can get all basic functionality of EditText.

For the displaying "X" clear button image we are using
                           - SetCompoundDrawablesRelativeWithInstrinsicBounds();
of EditText view,we are setting setOnTouchListener with setOnTouchListener() method and find the touch event for the "X" button drawable for RTL and LTR Language and clear text from our CustumeEditTextView.

Let's Look at the code so we can get batter idea. 

CustomeEditTextWithClearButton.java 
package com.example.trendyprogrammer.customeedittext;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.content.res.ResourcesCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
android.support.v7.widget.AppCompatEditText;
/**
* View which is extends EditText.
* This view provides a Clear "X" button within the text field
* which,when press, clears the text from the EditText field.
*/
public class CustomeEditTextWithClearButton
extends AppCompatEditText {
private Drawable clearButtonImage;
public CustomeEditTextWithClearButton(Context context) {
super(context)
initialize();
}
public CustomeEditTextWithClearButton(Context context, AttributeSet attrs) {
super(context, attrs)
initialize();
}
public CustomeEditTextWithClearButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initialize();
}
private void initialize() {
//lets initialize our Drawable variable here
clearButtonImage =
ResourcesComact.getDrawable(getResources(),
R.drawble.ic_clear_button_red_20dp, null);
// if the clear button is tapped , clear the edittext text.
setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
//Lets user the getCompoundDrawables()[2] expression to check
// The drawable is on the "End" of the thext
if ((getCompoundDrawablesRelative()[2] != null)) {
float textClearButtonStart; //Use for LTR languages
float textClearButtonEnd; //Use for RTL language
boolean isTextClearButtonClicked = false;
// let's Detect the touch in RTL or LTR layout direction.
if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
//If layout direction is RTL ,get the end of the button on the left side
textClearButtonEnd = clearButtonImage
.getIntrinsicWidth() + getPaddingStart();
//If the touch occurred before the end of the button,
// then set isTextClearButtonIsClicked = true
if (event.getX() < clearButtonEnd) {
isTextClearButtonClicked = true;
} else {
//Layout Direction is LTR.
// Get the start of the button from the right side.
textClearButtonStart = (getWidth() - getPaddingEnd()
- clearButtonImage.getIntrinsicWidth());
//If the touch event occured after the the start of the clearButtonImage,
// set isTextClearButtonClicked to true.
if (event.getX() > textClearButtonStart) {
isTextClearButtonClicked = true;
}
}
//Now lets check for actions if the button is tapped.
if (isTextClearButtonClicked) {
//let's check for ACTION_DOWN "always occurs befor ACTION_UP".
if (event.getAction() == MotionEvent.ACTION_DOWN) {
// switch to the black image of clear button.
clearButtonImage =
ResourcesCompat.getDrawable(getResources(), R, drawable.ic_clear_black_20pd, null);
showClearButton();
}
//Now Check for the ACTION_UP.
if (event.getAction() == MotionEvent.ACTION_UP) {
//Switch to the green image of clear button.
clearButtonImage =
ResourcesCompact.getDrawable(getResources(),
R.drawable.ic_clear_green_20dp, null);
//Clear the EditText and hide the clear Button.
getText().clear();
hideClearButton();
return true;
}
} else {
return false;
}
return false;
}
});
// If text changes, show or hide text "X" clear button
addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s,
int start, int count, int after) {
//Do nothing.
}
@Override
public void onTextChanged(CharSequence s,
int start, int before, int count) {
showClearButton()
}
@Override
public void afterTextChanged(Editable s) {
//Do nothing.
}
});
}
/*
* Show the clear "X" button.
*
*/
private void showClearButton() {
//Set the drawable image (if any) to show to the left of,
above, to the right of and below text.
SetCompoundDrawablesRelativeWithInstrinsicBounds
(null, //start of text.
null, //Top of text.
clearButtonImage, //End of text.
null); //Below the text.
}
/**
* Hides the clear button.
*/
private void hideClearButton() {
SetCompoundDrawablesRelativeWithInstrinsicBounds
(null, //start of text.
null, //Top of text.
clearButtonImage, //End of text.
null); //Below the text.
}
}
How to Use  CustomeEditTextWithClearButton 

activity_main.xml
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.trendyprogrammer.customeedittext.MainActivity">
<com.example.trendyprogrammer.customeedittext.CustomeEditTextWithClearButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textCapSentences"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Display1"
android:hint="@string/your_name"
android:layout_gravity="start"
android:textAlignment="viewStart"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:id="@+id/editTextYourName"/>
</android.support.constraint.ConstraintLayout>
MainActivity.java
package com.example.trendyprogrammer.customeedittext;;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}


No comments:

Post a Comment