Android输入框控件ClearEditText实现清除功能

2019-12-10 18:02:22于海丽
word" android:layout_marginLeft="10dip" android:layout_marginRight="10dip" android:layout_marginTop="10dip" android:drawableLeft="@drawable/account_icon" android:hint="输入密码" android:singleLine="true" android:password="true" android:drawableRight="@drawable/delete_selector" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/username" android:background="@drawable/login_edittext_bg" > </com.example.clearedittext.ClearEditText> <Button android:id="@+id/login" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dip" android:layout_marginRight="10dip" android:background="@drawable/login_button_bg" android:textSize="18sp" android:textColor="@android:color/white" android:layout_below="@+id/password" android:layout_marginTop="25dp" android:text="登录" /> </RelativeLayout>

  
然后就是界面代码的编写,主要是测试输入框左右晃动而已,比较简单

package com.example.clearedittext; 
 
import android.app.Activity; 
import android.os.Bundle; 
import android.text.TextUtils; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.Toast; 
 
public class MainActivity extends Activity { 
  private Toast mToast; 
 
  @Override 
  protected 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); 
     
    ((Button) findViewById(R.id.login)).setOnClickListener(new OnClickListener() { 
       
      @Override 
      public void onClick(View v) { 
        if(TextUtils.isEmpty(username.getText())){ 
          //设置晃动 
          username.setShakeAnimation(); 
          //设置提示 
          showToast("用户名不能为空"); 
          return; 
        } 
         
        if(TextUtils.isEmpty(password.getText())){ 
          password.setShakeAnimation(); 
          showToast("密码不能为空"); 
          return; 
        } 
      } 
    }); 
  } 
   
  /** 
   * 显示Toast消息 
   * @param msg 
   */ 
  private void showToast(String msg){ 
    if(mToast == null){ 
      mToast = Toast.makeText(this, msg, Toast.LENGTH_SHORT); 
    }else{ 
      mToast.setText(msg); 
    } 
    mToast.show(); 
  } 
 
 
}