EditText and edittext

Source: Internet
Author: User

EditText and edittext

Today, I learned about the custom control and made a user login widget EditText, which adds a small icon to the right of the Android system input box. Click the small icon to clear the content in the input box, however, Android native EditText does not provide this function, so to implement this function, we need to rewrite EditText.

First, I wrote it using Android studio. The Code has been shared to my github. If you need it, you can download it.

We can set an image for the input box at the top, bottom, and left, so we can set our Delete small icon using the property android: drawableRight,

 

 

Here we have set the pictures on the left and right. If we can set a listener for the pictures on the right, click the picture on the right to clear the content of the input box and hide the delete icon. This small function can be easily solved, however, Android does not allow us to add a listening function to the small icon on the right. At this time, do you find that this path is not working? Actually, we may simulate click events and use the onTouchEvent () in the input box () method to simulate,

 

When we touch up (that is, when ACTION_UP), the horizontal direction of the range is greater than the distance from the left side of the input box to the left side of the clear icon, and the distance from the left side of the input box to the right side of the clear image, the vertical direction is greater than the distance from the top of the input box to the top of the clear icon, less than the distance from the bottom of the input box to the clear icon, we think it is to click to clear the image, you only need to clear the small icon and listen to it. The shaking effect is also set for the input box. If you do not enter an account, click Login to shake the input box. Paste the code below. (The Code has detailed comments)

 

Package com. tony. clearedittext; import android. content. context; import android. graphics. rect; import android. graphics. drawable. drawable; import android. text. editable; import android. text. textWatcher; import android. util. attributeSet; import android. view. motionEvent; import android. view. view; import android. view. animation. animation; import android. view. animation. cycleInterpolator; import android. view. animation. TranslateAnimation; import android. widget. editText; import java. util. jar. attributes;/*** Created by Cheng Bao on 2015/6/17. */public class ClearEditText extends EditText implements View. onFocusChangeListener, TextWatcher {/*** reference of the delete button */private Drawable mClearDrawable; private Context context;/*** check whether the control has focus */private boolean hasFocus; public ClearEditText (Context context) {this (context, null );/ /Super (context); // this. context = context; // init ();} public ClearEditText (Context context, AttributeSet attrs) {// The constructor is also important, without this attribute, you cannot define this (context, attrs, android. r. attr. editTextStyle);} public ClearEditText (Context context, AttributeSet attrs, int defStyle) {super (context, attrs, defStyle); init ();} private void init () {// obtain DrawableRight of EditText. If it is not set, use the default image mClearDrawable = GetCompoundDrawables () [2]; if (mClearDrawable = null) {mClearDrawable = getResources (). getDrawable (R. drawable. delete_selector);} mClearDrawable. setBounds (0, 0, mClearDrawable. getIntrinsicWidth (), mClearDrawable. getIntrinsicHeight (); // by default, the hidden icon setClearIconVisible (false) is set. // setOnFocusChangeListener (this) is used to set a listener with a changed focus ); // set the listener addTextChangedListener (this);} @ Override public boolean onTo whose content is changed in the input box UchEvent (MotionEvent event) {if (mClearDrawable! = Null & event. getAction () = MotionEvent. ACTION_UP) {int x = (int) event. getX (); // determines whether the touch point is within the horizontal range. boolean isInnerWidth = (x> (getWidth ()-getTotalPaddingRight () & (x <(getWidth () -getPaddingRight (); // gets the border of the delete icon and returns a Rect object Rect rect = mClearDrawable. getBounds (); // get the int height = rect of the deleted icon. height (); int y = (int) event. getY (); // calculate the distance from the bottom of the icon to the bottom of the Control. int distance = (getHeight ()-height)/2; // Determine whether the touch point is in the vertical range (which may be slightly different) // The ordinate of the touch point is within the distance (distance + height of the icon itself, the deletion icon boolean isInnerHeight = (y> distance) & (y <(distance + height); if (isInnerHeight & isInnerWidth) {this. setText ("") ;}} return super. onTouchEvent (event);}/*** sets the display and hide of the clear icon. Call setCompoundDrawables to draw the EditText file ** @ param visible */private void setClearIconVisible (boolean visible) {Drawable right = visible? MClearDrawable: null; setCompoundDrawables (getCompoundDrawables () [0], getCompoundDrawables () [1], right, getCompoundDrawables () [3]);} /*** when the ClearEditText focus changes, determine whether the string length settings in the clear icon display and hide */@ Override public void onFocusChange (View v, boolean hasFocus) {this. hasFocus = hasFocus; if (hasFocus) {setClearIconVisible (getText (). length ()> 0) ;}else {setClearIconVisible (false );}} /*** callback method when the content in the input box changes */@ Override public void onTextChanged (CharSequence text, int start, int lengthBefore, int lengthAfter) {if (hasFocus) {setClearIconVisible (text. length ()> 0) ;}}@ Override public void beforeTextChanged (CharSequence s, int start, int count, int after) {}@ Override public void afterTextChanged (Editable s) {}/*** set shaking animation */public void setShakeAnimation () {this. startAnimation (shakeAnimation (5);}/*** shake Animation ** @ param counts 1 second shake how many times * @ return */public static Animation shakeAnimation (int counts) {Animation translateAnimation = new TranslateAnimation (0, 10, 0, 0); translateAnimation. setInterpolator (new CycleInterpolator (counts); translateAnimation. setDuration (1000); return translateAnimation ;}}

 

  • SetClearIconVisible () method: sets the method for hiding and displaying the clear icon. The setVisibility () method is not called here. setVisibility () is for View. We can call setCompoundDrawables (Drawable left, drawable top, Drawable right, Drawable bottom ).
  • SetOnFocusChangeListener (this) sets a focus change listener for the input box. If the input box has a focus, we can determine whether the value of the input box is null. If it is null, the clear icon is hidden; otherwise, the listener is displayed.
  • AddTextChangedListener (this) is used to set the content change listener for the input box. It is actually very simple. When the content in the input box changes, we need to clear the small icon for display and hiding, if the content length is not 0, it will be displayed. If it is not 0, it will be hidden. However, we need the focus in the input box to change the display or hide. Why do we need the focus? For example, we have a login interface, we saved the user name and password. When logging on to the onCreate () interface, we showed the password we saved in the user name input box and password input box, and the content in the input box changed, as a result, the clear icon in the user name input box and password input box is displayed. This is obviously not what we want, so we have added a focus judgment.
  • SetShakeAnimation (): This method is used to shake the left and right sides of the input box. When the user name is incorrect, the input box is jitters. In fact, it mainly uses a mobile animation and sets the animation's change rate to a sine curve.

Next we will use it, Activity layout, two custom input boxes, one button

<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: layout_width = "match_parent" android: layout_height = "match_parent" android: paddingLeft = "@ dimen/plugin" android: paddingRight = "@ dimen/plugin" android: paddingTop = "@ dimen/activity_vertical_margin" android: paddingBottom = "@ dimen/plugin" android: background = "#95CAE4" tools: context = ". mainActivity "> <com. tony. clearedittext. clearEditText android: id = "@ + id/username" android: layout_marginTop = "60dp" android: background = "@ drawable/login_edittext_bg" android: drawableLeft = "@ drawable/icon_user" android: layout_marginLeft = "10dip" android: layout_marginRight = "10dip" android: singleLine = "true" android: drawableRight = "@ drawable/delete_selector" android: hint = "input username" android: layout_width = "match_parent" android: layout_height = "wrap_content"/> <com. tony. clearedittext. clearEditText android: id = "@ + id/password" android: layout_marginLeft = "10dip" android: layout_marginRight = "10dip" android: layout_marginTop = "10dip" android: drawableLeft = "@ drawable/account_icon" android: hint = "Enter password" android: singleLine = "true" android: password = "true" android: drawableRight = "@ drawable/delete_selector" android: layout_below = "@ + id/username" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: background = "@ drawable/login_edittext_bg"/> <Button android: id = "@ + id/login" android: layout_marginLeft = "10dip" android: layout_marginRight = "10dip" android: background = "@ drawable/login_button_bg" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: textSize = "18sp" android: textColor = "@ android: color/white "android: layout_below =" @ + id/password "android: layout_marginTop =" 25dp "android: text =" login "/> </RelativeLayout>

Then there is the compilation of the interface code, mainly the shaking of the test input box left and right

 

Package com. tony. clearedittext; import android. app. activity; import android. support. v7.app. actionBarActivity; import android. OS. bundle; import android. text. textUtils; import android. view. menu; import android. view. menuItem; import android. view. view; import android. widget. button; import android. widget. toast; public class MainActivity extends Activity {private Toast mToast; private Button mButton; @ Override pr Otected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); final ClearEditText username = (ClearEditText) findViewById (R. id. username); final ClearEditText password = (ClearEditText) findViewById (R. id. password); mButton = (Button) findViewById (R. id. login); mButton. setOnClickListener (new View. onClickListener () {@ Override public voi D onClick (View v) {if (TextUtils. isEmpty (username. getText () {// set to shake username. setShakeAnimation (); // The showToast prompt is displayed. ("the user name cannot be blank! "); Return;} if (TextUtils. isEmpty (password. getText () {password. setShakeAnimation (); showToast (" the password cannot be blank! "); Return ;}});}/*** display the Toast message * @ param msg */private void showToast (String msg) {if (mToast = null) {mToast = Toast. makeText (this, msg, Toast. LENGTH_SHORT);} else {mToast. setText (msg);} mToast. show ();}}

 

As follows:

Project Source: https://github.com/tonycheng93/Android-CustomLoginDemo

If you need a friend or a learning partner, hurry up.

In the course of learning, an article on CSDN has helped me a lot. To a large extent, I have learned from this excellent blog: http://blog.csdn.net/xiaanming/article/details/11066685 (note: the original author in the clear icon listening did not consider the vertical direction, in addition, the input box shake effect is not achieved, I checked some information to add these two functions)

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.