如何在单击时清除 EditText?

发布于 2024-10-02 07:06:10 字数 150 浏览 3 评论 0原文

在 Android 中,如何在单击 EditText 时使其清晰?

例如,如果我有一个 EditText ,其中包含一些字符,例如 'Enter Name',当用户单击它时,这些字符就会消失。

In Android how can I make an EditText clear when it's clicked?

E.g., if I have an EditText with some characters in, such as 'Enter Name', when the user clicks on it these characters disappear.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

愁杀 2024-10-09 07:06:10

我不确定您是否需要此操作,但请尝试此 XML:

android:hint="Enter Name"

当输入字段为空、选定或未选定时,它会显示该文本。

或者,如果您希望它完全按照您的描述进行操作,请在 editText 上分配一个 onClickListener 并使用 setText() 将其设置为空。

I'm not sure if you are after this, but try this XML:

android:hint="Enter Name"

It displays that text when the input field is empty, selected or unselected.

Or if you want it to do exactly as you described, assign a onClickListener on the editText and set it empty with setText().

云淡月浅 2024-10-09 07:06:10

您是否正在寻找类似于 iPhone 上文本字段右侧显示的 x 的行为,点击后会清除文本?那里称为clearButtonMode。以下是如何在 Android EditText 视图中创建相同的功能:

String value = "";//any text you are pre-filling in the EditText

final EditText et = new EditText(this);
et.setText(value);
final Drawable x = getResources().getDrawable(R.drawable.presence_offline);//your x image, this one from standard android images looks pretty good actually
x.setBounds(0, 0, x.getIntrinsicWidth(), x.getIntrinsicHeight());
et.setCompoundDrawables(null, null, value.equals("") ? null : x, null);
et.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (et.getCompoundDrawables()[2] == null) {
            return false;
        }
        if (event.getAction() != MotionEvent.ACTION_UP) {
            return false;
        }
        if (event.getX() > et.getWidth() - et.getPaddingRight() - x.getIntrinsicWidth()) {
            et.setText("");
            et.setCompoundDrawables(null, null, null, null);
        }
        return false;
    }
});
et.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        et.setCompoundDrawables(null, null, et.getText().toString().equals("") ? null : x, null);
    }

    @Override
    public void afterTextChanged(Editable arg0) {
    }

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

Are you looking for behavior similar to the x that shows up on the right side of text fields on an iphone that clears the text when tapped? It's called clearButtonMode there. Here is how to create that same functionality in an Android EditText view:

String value = "";//any text you are pre-filling in the EditText

final EditText et = new EditText(this);
et.setText(value);
final Drawable x = getResources().getDrawable(R.drawable.presence_offline);//your x image, this one from standard android images looks pretty good actually
x.setBounds(0, 0, x.getIntrinsicWidth(), x.getIntrinsicHeight());
et.setCompoundDrawables(null, null, value.equals("") ? null : x, null);
et.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (et.getCompoundDrawables()[2] == null) {
            return false;
        }
        if (event.getAction() != MotionEvent.ACTION_UP) {
            return false;
        }
        if (event.getX() > et.getWidth() - et.getPaddingRight() - x.getIntrinsicWidth()) {
            et.setText("");
            et.setCompoundDrawables(null, null, null, null);
        }
        return false;
    }
});
et.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        et.setCompoundDrawables(null, null, et.getText().toString().equals("") ? null : x, null);
    }

    @Override
    public void afterTextChanged(Editable arg0) {
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }
});
萌︼了一个春 2024-10-09 07:06:10

onclick 任何操作后,执行以下步骤

((EditText) findViewById(R.id.yoursXmlId)).setText("");

将其写入 XML 文件,

<EditText
---------- other stuffs ------ 
android:hint="Enter Name" /> 

它对我来说效果很好。希望大家。

after onclick of any action do below step

((EditText) findViewById(R.id.yoursXmlId)).setText("");

or

write this in XML file

<EditText
---------- other stuffs ------ 
android:hint="Enter Name" /> 

its works fine for me. Hope to you all.

零度° 2024-10-09 07:06:10

这在android中称为提示
使用
android:hint="输入名称"

that is called hint in android
use
android:hint="Enter Name"

揽月 2024-10-09 07:06:10

@Harris 的答案很棒,我已将其实现为 EditText 的单独子类,如果您的代码已经添加了 TextChangedListeners,这可以使其更易于使用。

另外,我还对其进行了调整,这样,如果您已经使用了任何复合绘图,它就可以保持它们完好无损。

代码在这里,供有需要的人使用:

package com.companyname.your

import android.content.Context;
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.widget.EditText;

public class ClearableEditText extends EditText {

    public String defaultValue = "";
    final Drawable imgX = getResources().getDrawable(android.R.drawable.presence_offline ); // X image


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

        init();
    }

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

        init();
    }

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

        init();
    }


    void init()  {

        // Set bounds of our X button
        imgX.setBounds(0, 0, imgX.getIntrinsicWidth(), imgX.getIntrinsicHeight());      

        // There may be initial text in the field, so we may need to display the button
        manageClearButton();

        this.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                ClearableEditText et = ClearableEditText.this;

                // Is there an X showing?
                if (et.getCompoundDrawables()[2] == null) return false;
                // Only do this for up touches
                if (event.getAction() != MotionEvent.ACTION_UP) return false;
                // Is touch on our clear button?
                if (event.getX() > et.getWidth() - et.getPaddingRight() - imgX.getIntrinsicWidth()) {
                    et.setText("");
                    ClearableEditText.this.removeClearButton();
                }
                return false;
            }
        });

        this.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                ClearableEditText.this.manageClearButton();
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }

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

    void manageClearButton() {
        if (this.getText().toString().equals("") )
            removeClearButton();
        else
            addClearButton();
    }
    void addClearButton() {
        this.setCompoundDrawables(this.getCompoundDrawables()[0], 
                this.getCompoundDrawables()[1],
                imgX,
                this.getCompoundDrawables()[3]);
    }
    void removeClearButton() {
        this.setCompoundDrawables(this.getCompoundDrawables()[0], 
                this.getCompoundDrawables()[1],
                null,
                this.getCompoundDrawables()[3]);
    }

}

@Harris's answer is great, I've implemented it as a separate subclass of EditText, which can make it easier to use if your code already adds TextChangedListeners.

Also, I've tweaked it so that, if you already use any Compound Drawables, it leaves them intact.

Code is here, for anyone who needs it:

package com.companyname.your

import android.content.Context;
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.widget.EditText;

public class ClearableEditText extends EditText {

    public String defaultValue = "";
    final Drawable imgX = getResources().getDrawable(android.R.drawable.presence_offline ); // X image


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

        init();
    }

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

        init();
    }

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

        init();
    }


    void init()  {

        // Set bounds of our X button
        imgX.setBounds(0, 0, imgX.getIntrinsicWidth(), imgX.getIntrinsicHeight());      

        // There may be initial text in the field, so we may need to display the button
        manageClearButton();

        this.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                ClearableEditText et = ClearableEditText.this;

                // Is there an X showing?
                if (et.getCompoundDrawables()[2] == null) return false;
                // Only do this for up touches
                if (event.getAction() != MotionEvent.ACTION_UP) return false;
                // Is touch on our clear button?
                if (event.getX() > et.getWidth() - et.getPaddingRight() - imgX.getIntrinsicWidth()) {
                    et.setText("");
                    ClearableEditText.this.removeClearButton();
                }
                return false;
            }
        });

        this.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                ClearableEditText.this.manageClearButton();
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }

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

    void manageClearButton() {
        if (this.getText().toString().equals("") )
            removeClearButton();
        else
            addClearButton();
    }
    void addClearButton() {
        this.setCompoundDrawables(this.getCompoundDrawables()[0], 
                this.getCompoundDrawables()[1],
                imgX,
                this.getCompoundDrawables()[3]);
    }
    void removeClearButton() {
        this.setCompoundDrawables(this.getCompoundDrawables()[0], 
                this.getCompoundDrawables()[1],
                null,
                this.getCompoundDrawables()[3]);
    }

}
穿透光 2024-10-09 07:06:10

如果您想在编辑文本中包含文本并像您所说的那样将其删除,请尝试:

    final EditText text_box = (EditText) findViewById(R.id.input_box);
    text_box.setOnFocusChangeListener(new OnFocusChangeListener()
    {
        @Override
        public void onFocusChange(View v, boolean hasFocus) 
        {
            if (hasFocus==true)
            {
                if (text_box.getText().toString().compareTo("Enter Text")==0)
                {
                    text_box.setText("");
                }
            }
        }
    });

If you want to have text in the edit text and remove it like you say, try:

    final EditText text_box = (EditText) findViewById(R.id.input_box);
    text_box.setOnFocusChangeListener(new OnFocusChangeListener()
    {
        @Override
        public void onFocusChange(View v, boolean hasFocus) 
        {
            if (hasFocus==true)
            {
                if (text_box.getText().toString().compareTo("Enter Text")==0)
                {
                    text_box.setText("");
                }
            }
        }
    });
紫轩蝶泪 2024-10-09 07:06:10

在要设置文本的字段上使用 onClick 侦听器设置文本时要小心。我正在这样做并将文本设置为空字符串。这导致指针出现以指示我的光标所在的位置,该指针通常会在几秒钟后消失。当我没有等到它消失就离开我的页面导致调用 finish() 时,它会导致内存泄漏并使我的应用程序崩溃。我花了一段时间才找出导致崩溃的原因。

无论如何,如果可以的话,我建议您在单击侦听器中使用 selectAll() 而不是 setText() 。这样,一旦选择了文本,用户就可以开始输入,并且之前的所有文本都将被清除。

可疑指针的图片:https://i.sstatic.net/juJnt.png

Be careful when setting text with an onClick listener on the field you are setting the text. I was doing this and setting the text to an empty string. This was causing the pointer to come up to indicate where my cursor was, which will normally go away after a few seconds. When I did not wait for it to go away before leaving my page causing finish() to be called, it would cause a memory leak and crash my app. Took me a while to figure out what was causing the crash on this one..

Anyway, I would recommend using selectAll() in your on click listener rather than setText() if you can. This way, once the text is selected, the user can start typing and all of the previous text will be cleared.

pic of the suspect pointer: https://i.sstatic.net/juJnt.png

通知家属抬走 2024-10-09 07:06:10

//点击清除按钮时清除

firstName = (EditText) findViewById(R.id.firstName);

    clear = (Button) findViewById(R.id.clearsearchSubmit);

    clear.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (v.getId() == R.id.clearsearchSubmit);
            firstName.setText("");
        }
    });

这将有助于清除您输入的错误关键字,因此您无需一次又一次地按退格键,只需单击按钮即可清除所有内容。这对我有用。希望有帮助

//To clear When Clear Button is Clicked

firstName = (EditText) findViewById(R.id.firstName);

    clear = (Button) findViewById(R.id.clearsearchSubmit);

    clear.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (v.getId() == R.id.clearsearchSubmit);
            firstName.setText("");
        }
    });

This will help to clear the wrong keywords that you have typed in so instead of pressing backspace again and again you can simply click the button to clear everything.It Worked For me. Hope It Helps

丿*梦醉红颜 2024-10-09 07:06:10

单击时清除文本字段的代码

<EditText android:onClick="TextFieldClicked"/>

public void TextFieldClicked(View view){      
      if(view.getId()==R.id.editText1);
           text.setText("");    
}

Code for clearing up the text field when clicked

<EditText android:onClick="TextFieldClicked"/>

public void TextFieldClicked(View view){      
      if(view.getId()==R.id.editText1);
           text.setText("");    
}
梦初启 2024-10-09 07:06:10

对我来说最简单的方法...
创建一个公共 EditText,例如“myEditText1”

public EditText myEditText1;

然后,将其与应该清除的 EditText 连接起来

myEditText1 = (EditText) findViewById(R.id.numberfield);

之后,创建一个对 EditText 的单击做出反应的空洞,并让它在聚焦时清除其中的文本,例如

@OnClick(R.id.numberfield)
        void textGone(){
            if (myEditText1.isFocused()){
                myEditText1.setText("");

        }
    }

Hope我可以帮助你,祝大家度过愉快的一天

For me the easiest way...
Create an public EditText, for Example "myEditText1"

public EditText myEditText1;

Then, connect it with the EditText which should get cleared

myEditText1 = (EditText) findViewById(R.id.numberfield);

After that, create an void which reacts to an click to the EditText an let it clear the Text inside it when its Focused, for Example

@OnClick(R.id.numberfield)
        void textGone(){
            if (myEditText1.isFocused()){
                myEditText1.setText("");

        }
    }

Hope i could help you, Have a nice Day everyone

一江春梦 2024-10-09 07:06:10

对于 kotlin 的朋友:

edtxt1.onFocusChangeListener = OnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                edtxt1.text = ""
            }
        }

在此处输入图像描述

For kotlin's friends:

edtxt1.onFocusChangeListener = OnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                edtxt1.text = ""
            }
        }

enter image description here

吾家有女初长成 2024-10-09 07:06:10
((EditText) findViewById(R.id.User)).setText("");
((EditText) findViewById(R.id.Password)).setText("");
((EditText) findViewById(R.id.User)).setText("");
((EditText) findViewById(R.id.Password)).setText("");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文