1. 程式人生 > >Android開發中實現帶有刪除圖示的EditText輸入框

Android開發中實現帶有刪除圖示的EditText輸入框

效果圖如下:

備註:附帶一個隱藏和顯示密碼的功能實現。

activity_main.xml佈局檔案的程式碼如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dp"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <com.deepreality.userdefinededittextdemo.DelEditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:hint="帶有刪除的EditText"
        android:textSize="14dp"
        android:background="@drawable/edittext_search"
        android:maxLength="20"
        android:paddingRight="10dp"
        android:paddingLeft="5dp"
        android:singleLine="true"/>

    <LinearLayout android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/edit_pawd"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="48dp"
            android:inputType="textPassword"
            android:background="@drawable/edittext_search"/>

        <CheckBox
            android:id="@+id/cbChange"
            android:layout_width="100dp"
            android:layout_height="48dp"
            android:text="密碼可見"/>

    </LinearLayout>


</LinearLayout>

其中的EditText樣式,自定義一個Shape樣式。可以參考之前的安卓開發中TextView的常見用法(總結),如果忘記的話。

佈局檔案中的EditText是自定義的。DelEditText.java的程式碼如下:

package com.deepreality.userdefinededittextdemo;

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;

public class DelEditText extends android.support.v7.widget.AppCompatEditText {

    private Context context;
    private Drawable drawableDel;

    public DelEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }

    private void init() {
        //給Drawable賦值
        drawableDel = context.getResources().getDrawable(R.mipmap.edittext_delete);
        //新增文字內容變化監聽事件
        addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setDrawable();
            }
        });
    }

    //繪製刪除圖片
    private void setDrawable() {
        if (length() < 1) {
            setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        } else {
            setCompoundDrawablesWithIntrinsicBounds(null, null, drawableDel, null);
        }
    }

    //當觸控範圍在右側時,觸發刪除方法,隱藏刪除圖片
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (drawableDel != null && event.getAction() == MotionEvent.ACTION_UP) {
            int eventX = (int) event.getRawX();
            int eventY = (int) event.getRawY();
            Rect rect = new Rect();
            getGlobalVisibleRect(rect);
            rect.left = rect.right - 100;
            if (rect.contains(eventX, eventY)) {
                setText("");
            }
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
    }
}

接下來,我們只要在相關的Activity中處理即可。

MainActivity.java的程式碼如下:

package com.deepreality.userdefinededittextdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    private EditText edit_pawd;
    private CheckBox cbChange;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edit_pawd = (EditText) findViewById(R.id.edit_pawd);
        cbChange = (CheckBox) findViewById(R.id.cbChange);
        edit_pawd.setHorizontallyScrolling(true);    //設定EditText不換行
        cbChange.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    //顯示密碼
                    edit_pawd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    //不顯示密碼
                    edit_pawd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });
    }
}