1. 程式人生 > >Android帶刪除圖示的EditText

Android帶刪除圖示的EditText

今天寫了一個簡單的登入介面,輸入框總是很醜,加上刪除按鈕就感覺順眼多了,記錄一下。

看效果圖:

下面上程式碼:

1.ClearEditText

public class ClearEditText extends EditText implements
        OnFocusChangeListener, TextWatcher {
    /**
     * 刪除按鈕的引用
     */
    private Drawable mClearDrawable;
    /**
     * 控制元件是否有焦點
     */
    private boolean hasFoucs;

    public ClearEditText(Context context) {
        this(context, null);
    }

    public ClearEditText(Context context, AttributeSet attrs) {
        //這裡構造方法也很重要,不加這個很多屬性不能再XML裡面定義
        this(context, attrs, android.R.attr.editTextStyle);
    }

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


    private void init() {
        //獲取EditText的DrawableRight,假如沒有設定我們就使用預設的圖片
        mClearDrawable = getCompoundDrawables()[2];
        if (mClearDrawable == null) {
//          throw new NullPointerException("You can add drawableRight attribute in XML");
            mClearDrawable = getResources().getDrawable(R.mipmap.delete2);
        }

        /**
         * setBounds(x,y,width,height);
         * x:元件在容器X軸上的起點
         * y:元件在容器Y軸上的起點
         * width:元件的長度
         * height:元件的
         */

        mClearDrawable.setBounds(-30, 0, 30, 60);
        //預設設定隱藏圖示
        setClearIconVisible(false);
        //設定焦點改變的監聽
        setOnFocusChangeListener(this);
        //設定輸入框裡面內容發生改變的監聽
        addTextChangedListener(this);
    }


    /**
     * 因為我們不能直接給EditText設定點選事件,所以我們用記住我們按下的位置來模擬點選事件
     * 當我們按下的位置 在  EditText的寬度 - 圖示到控制元件右邊的間距 - 圖示的寬度  和
     * EditText的寬度 - 圖示到控制元件右邊的間距之間我們就算點選了圖示,豎直方向就沒有考慮
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (getCompoundDrawables()[2] != null) {

                boolean touchable = event.getX() > (getWidth() - getTotalPaddingRight())
                        && (event.getX() < ((getWidth() - getPaddingRight())));

                if (touchable) {
                    this.setText("");
                }
            }
        }

        return super.onTouchEvent(event);
    }

    /**
     * 當ClearEditText焦點發生變化的時候,判斷裡面字串長度設定清除圖示的顯示與隱藏
     */
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        this.hasFoucs = hasFocus;
        if (hasFocus) {
            setClearIconVisible(getText().length() > 0);
        } else {
            setClearIconVisible(false);
        }
    }


    /**
     * 設定清除圖示的顯示與隱藏,呼叫setCompoundDrawables為EditText繪製上去
     * @param visible
     */
    protected void setClearIconVisible(boolean visible) {
        Drawable right = visible ? mClearDrawable : null;
        setCompoundDrawables(getCompoundDrawables()[0],
                getCompoundDrawables()[1], right, getCompoundDrawables()[3]);
    }


    /**
     * 當輸入框裡面內容發生變化的時候回撥的方法
     */
    @Override
    public void onTextChanged(CharSequence s, int start, int count,
                              int after) {
        if(hasFoucs){
            setClearIconVisible(s.length() > 0);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {

    }

    @Override
    public void afterTextChanged(Editable s) {

    }


    /**
     * 設定晃動動畫
     */
    public void setShakeAnimation(){
        this.setAnimation(shakeAnimation(5));
    }


    /**
     * 晃動動畫
     * @param counts 1秒鐘晃動多少下
     * @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;
    }


}
2.edittext_background.xml
<?xml version="1.0" encoding="utf-8"?><!--定義一個帶圓角,白色背景,綠色邊框的矩形-->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <!--填充顏色-->
    <solid android:color="#fff" />
    <!--描邊-->
    <stroke
        android:width="1dp"
        android:color="#878787" />
    <!--圓角弧度-->
    <corners android:radius="30dp"/>
</shape>

3.activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="visahall.cn.testedittext.MainActivity">

    <visahall.cn.testedittext.ClearEditText
        android:id="@+id/clear"
        android:paddingLeft="10dp"
        android:background="@drawable/edittext_background"
        android:layout_width="match_parent"
        android:layout_height="40dp" />

    <Button
        android:id="@+id/btn"
        android:layout_below="@+id/clear"
        android:text="獲取輸入框的值"
        android:layout_width="match_parent"
        android:layout_height="50dp" />
</RelativeLayout>

4.MainActivity:

public class MainActivity extends AppCompatActivity {

    private ClearEditText clearEditText;
    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (clearEditText.getText().toString().length() != 0){
                    Toast.makeText(MainActivity.this, "值為:" + clearEditText.getText().toString(), Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(MainActivity.this, "null", Toast.LENGTH_SHORT).show();

                }

            }
        });

    }

    private void initView() {
        clearEditText = (ClearEditText) findViewById(R.id.clear);
        button = (Button) findViewById(R.id.btn);
    }
}