Android Addicted Apps Creator

February 20, 2012

Android EditText with custom font and clear button

Filed under: Android — alinberce @ 20:22
Tags: , , , , , ,

C’mon, admit it, you’ve always wanted this. Have you ever felt that text clearing in your android application on EditTexts feels… wrong ?

So, what do we want to achive?

Plain and simple, a TextView, based on the same principle as the previous TextView tutorial, with custom fonts (from assets folder) and with a Clear button.

image

Proceed with caution…

  Of course, if you get a request to use custom fonts in you app, this does not apply only to TextViews, but to all items like Buttons, List Items and EditTexts.

First we need to create our own custom control, extending EditText and adding the following:

  • an image resource for the Clear button
  • an TextChangedListener so we only show the Clear button when the EditText contains something
  • method for setting our custom TypeFace
  • TouchListener so we detect if the user taped on the Clear button area.

Our project will contain a few things:

image

  1. Main activity: AndroidTutorialActivity.java
  2. Our custom control: MyEditText
  3. Custom fonts in assets folder
  4. Clear_button_image resource for the button  image
  5. Main.xml as the main layout.

I’ll just post the entire code with comments and I’m sure you’ll understand it in a second:

public class MyEditText extends EditText{

	//The image we are going to use for the Clear button
	private Drawable imgCloseButton = getResources().getDrawable(R.drawable.clear_button_image);
	
	public MyEditText(Context context) {
		super(context);
		init();
	}

	public MyEditText(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	public MyEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}
	
	void init() {
		
		// Set bounds of the Clear button so it will look ok
		imgCloseButton.setBounds(0, 0, imgCloseButton.getIntrinsicWidth(), imgCloseButton.getIntrinsicHeight());

		// There may be initial text in the field, so we may need to display the  button
		handleClearButton();

		//if the Close image is displayed and the user remove his finger from the button, clear it. Otherwise do nothing
		this.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {

				MyEditText et = MyEditText.this;

				if (et.getCompoundDrawables()[2] == null)
					return false;
				
				if (event.getAction() != MotionEvent.ACTION_UP)
					return false;
				
				if (event.getX() > et.getWidth() - et.getPaddingRight() - imgCloseButton.getIntrinsicWidth()) {
					et.setText("");
					MyEditText.this.handleClearButton();
				}
				return false;
			}
		});

		//if text changes, take care of the button
		this.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

				MyEditText.this.handleClearButton();
			}

			@Override
			public void afterTextChanged(Editable arg0) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}
		});
	}
	
	//intercept Typeface change and set it with our custom font
    public void setTypeface(Typeface tf, int style) {
	    if (style == Typeface.BOLD) {
	        super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Vegur-B 0.602.otf"));
	    } else {
	        super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/Vegur-R 0.602.otf"));
	    }
    }
	
	void handleClearButton() {
		if (this.getText().toString().equals(""))
		{
			// add the clear button
			this.setCompoundDrawables(this.getCompoundDrawables()[0], this.getCompoundDrawables()[1], null, this.getCompoundDrawables()[3]);
		}
		else
		{
			//remove clear button
			this.setCompoundDrawables(this.getCompoundDrawables()[0], this.getCompoundDrawables()[1], imgCloseButton, this.getCompoundDrawables()[3]);
		}
	}
}

Don’t forget to add it in your main layout

 

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

    <com.alinberce.app.MyEditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="My cool edit text" />
</LinearLayout>

Run it and see the result:

 

image

Source code of the project can be found: HERE

image

Advertisements

6 Comments »

  1. Alin, poti sa faci te rog frumos cum sa schimbi fontul pe un Xperia Ray ? Fara root daca se poate. Mersi !

    Comment by Roby — February 22, 2012 @ 19:49 | Reply

    • Robi, acest tutorial este pentru developeri, cand fac aplicatii si vor sa foloseasca fonturi custom. Din pacate pe telefon, sa se aplice la toate aplicatiile nu poti face daca nu ai root (din cate stiu eu). Daca ai root, poti incerca: https://market.android.com/details?id=com.martino2k6.fontchangerlite banuiesc ca merge.

      Comment by alinberce — February 22, 2012 @ 19:53 | Reply

      • Pe Galaxy-uri poti fara root, ai Fontomizer (Galaxy SP) . Modele Xperia sunt ciudate rau….fara sa deblochez bootloader nu pot sa fac decat root temporar…stiu ca suna prostesc, ca deobicei root-ul nu are treaba cu bootloader-ul, dar Xperia sunt tare ciudate….Si bootloader-ul nu se mai rescrie…Acum intelegi problema, credeam ca e vreo metoda cu SDK, dar daca nu e asta e, sper ca in update-ul 4.0 Sony sa schimbe aceasta tampenie…

        Comment by Roby — February 22, 2012 @ 20:19

  2. Hi!!
    This is quite awesome example to customize the android edittext. But the imageview tries to keep it self in the center while adding multiline text. Can you tell me how I can keep the imageview on the top of the edittext.

    Thanks.

    Comment by Maverick — June 25, 2013 @ 09:36 | Reply

  3. […] Are you looking for edittext control with clear button? And what if it uses custom font too? Check tutorial at https://alinberce.wordpress.com/2012/02/20/android-edittext-with-custom-font-and-clear-button/ […]

    Pingback by Android EditText with custom font and clear button | S A N D R O I D — July 22, 2013 @ 17:29 | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: