web-dev-qa-db-ja.com

Android:右側のクロスボタンでEditTextをクリアする方法

検索用のEditTextを作成しました。これには、左側に検索アイコンが含まれ、アイコンの右側に次のアイコンが含まれています。

<EditText
    Android:id="@+id/Search"
    Android:layout_width="250dp"
    Android:layout_height="wrap_content"
    Android:drawableLeft="@Android:drawable/ic_menu_search"
    Android:drawableRight="@Android:drawable/ic_delete"
    Android:hint="Search Product .." >
</EditText>

クロスボタンをクリックしたときにEditTextのコンテンツをクリアする方法を知りたいです。

前もって感謝します。

15
Sarra

@aristo_shによる改善された回答 EditText内のドローアブルのクリックイベントの処理

    mQueryEditText.setOnTouchListener(new OnTouchListener() {
        final int DRAWABLE_LEFT = 0;
        final int DRAWABLE_TOP = 1;
        final int DRAWABLE_RIGHT = 2;
        final int DRAWABLE_BOTTOM = 3;
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                int leftEdgeOfRightDrawable = mQueryEditText.getRight() 
                      - mQueryEditText.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width();
                // when EditBox has padding, adjust leftEdge like
                // leftEdgeOfRightDrawable -= getResources().getDimension(R.dimen.edittext_padding_left_right);
                if (event.getRawX() >= leftEdgeOfRightDrawable) {
                    // clicked on clear icon
                    mQueryEditText.setText("");
                    return true;
                }
            }
            return false;
        }
    });
16
Paul Verest

以下のクリア可能な編集テキストとして、別のカスタムEdittexを使用することをお勧めします。通常の編集テキストとしてxmlで使用できます。クリアイベントを聞くには、setListenerClearableEdittextすることができます

/** Copyright 2014 Alex Yanchenko
 * To change clear icon, set
 * <p/>
 * <pre>
 * Android:drawableRight="@drawable/custom_icon"
 * </pre>
 */
public class ClearableEditText extends EditText implements OnTouchListener,
        OnFocusChangeListener, TextWatcherAdapter.TextWatcherListener {

    public interface Listener {
        void didClearText();
    }

    public void setListener(Listener listener) {
        this.listener = listener;
    }

    private Drawable xD;
    private Listener listener;

    public ClearableEditText(Context context) {
        super(context);
        init();
    }

    public ClearableEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

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

    @Override
    public void setOnTouchListener(OnTouchListener l) {
        this.l = l;
    }

    @Override
    public void setOnFocusChangeListener(OnFocusChangeListener f) {
        this.f = f;
    }

    private OnTouchListener l;
    private OnFocusChangeListener f;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (getCompoundDrawables()[2] != null) {
            boolean tappedX = event.getX() > (getWidth() - getPaddingRight() - xD
                    .getIntrinsicWidth());
            if (tappedX) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    setText("");
                    if (listener != null) {
                        listener.didClearText();
                    }
                }
                return true;
            }
        }
        if (l != null) {
            return l.onTouch(v, event);
        }
        return false;
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            setClearIconVisible(!TextUtils.isEmpty(getText()));
        } else {
            setClearIconVisible(false);
        }
        if (f != null) {
            f.onFocusChange(v, hasFocus);
        }
    }

    @Override
    public void onTextChanged(EditText view, String text) {
        if (isFocused()) {
            setClearIconVisible(!TextUtils.isEmpty(text));
        }
    }

    private void init() {
        xD = getCompoundDrawables()[2];
        if (xD == null) {
            xD = getResources()
                    .getDrawable(Android.R.drawable.presence_offline);
        }
        xD.setBounds(0, 0, xD.getIntrinsicWidth(), xD.getIntrinsicHeight());
        setClearIconVisible(false);
        super.setOnTouchListener(this);
        super.setOnFocusChangeListener(this);
        addTextChangedListener(new TextWatcherAdapter(this, this));
    }

    protected void setClearIconVisible(boolean visible) {
        Drawable x = visible ? xD : null;
        setCompoundDrawables(getCompoundDrawables()[0],
                getCompoundDrawables()[1], x, getCompoundDrawables()[3]);
    }
}

編集:TextWatcherAdapterを忘れましたが、実際にはTextWatcherだけです。

public class TextWatcherAdapter implements TextWatcher {

public interface TextWatcherListener {

    void onTextChanged(EditText view, String text);

}

private final EditText view;
private final TextWatcherListener listener;

public TextWatcherAdapter(EditText editText, TextWatcherListener listener) {
    this.view = editText;
    this.listener = listener;
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    listener.onTextChanged(view, s.toString());
}

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

@Override
public void afterTextChanged(Editable s) {
    // pass
}
}
5

これを試して:

activity_main.xml

<FrameLayout
    Android:layout_width="fill_parent"
    Android:layout_height="wrap_content"
    Android:layout_marginTop="9dp"
    Android:padding="5dp">

    <EditText
        Android:id="@+id/Search"
        Android:layout_width="250dp"
        Android:layout_height="wrap_content"
        Android:drawableLeft="@Android:drawable/ic_menu_search"
        Android:hint="Search Product .." >
    </EditText>

    <Button
        Android:id="@+id/clearText"
        Android:layout_width="23dp"
        Android:layout_height="23dp"
        Android:layout_marginRight="10dp"
        Android:layout_gravity="right|bottom"
        Android:layout_marginBottom="10dp"
        Android:background="@Android:drawable/ic_delete"
        Android:onClick="clear"/>

</FrameLayout>

MainActivity.Java

public class MainActivity extends AppCompatActivity {

    EditText mEditText;
    Button mClearText;

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

        mEditText = (EditText) findViewById(R.id.Search);
        mClearText = (Button) findViewById(R.id.clearText);

        //initially clear button is invisible
        mClearText.setVisibility(View.INVISIBLE);

        //clear button visibility on text change
        mEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable s) {
                //do nothing
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //do nothing
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(s.length() != 0) {
                    mClearText.setVisibility(View.VISIBLE);
                } else {
                    mClearText.setVisibility(View.GONE);
                }
            }
        });

    }

    //clear button onclick
    public void clear(View view) {
        mEditText.setText("");
        mClearText.setVisibility(View.GONE);
    }

}
2
Ashwin

私が作った例:

mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (motionEvent.getAction() == MotionEvent.ACTION_UP){
                // 100 is a fix value for the moment but you can change it
                // according to your view
                if (motionEvent.getX()>(view.getWidth()-100)){
                    ((EditText)view).setText("");
                }
            }
            return false;
        }
    });

    mPasswordView.addTextChangedListener(new TextWatcher() {

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

            if(s.toString().trim().length()==0){
                mPasswordView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
            } else {
                mPasswordView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_close_black_24dp, 0);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub
            mPasswordView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            if (s.toString().trim().length() == 0) {
                mPasswordView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
            } else {
                mPasswordView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_close_black_24dp, 0);
            }
        }
    });
0
Jacques Weber