Development Tip

클릭시 EditText를 지우는 방법은 무엇입니까?

yourdevel 2020. 11. 2. 19:50
반응형

클릭시 EditText를 지우는 방법은 무엇입니까?


Android EditText에서 클릭했을 때 어떻게 명확하게 할 수 있습니까?

예를 들어, EditText와 같은 일부 문자가있는 'Enter Name'경우 사용자가 클릭하면 이러한 문자가 사라집니다.


이 이후에 있는지 확실하지 않지만 다음 XML을 시도하십시오.

android:hint="Enter Name"

입력 필드가 비어 있거나 선택되거나 선택되지 않은 경우 해당 텍스트를 표시합니다.

또는 설명 된대로 정확하게 수행하려면 editText에 onClickListener를 할당하고 setText ()를 사용하여 비워 두십시오.


탭하면 텍스트를 지우는 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) {
    }
});

작업을 클릭 한 후 아래 단계를 수행하십시오.

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

또는

이것을 XML 파일로 작성하십시오.

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

그것은 나를 위해 잘 작동합니다. 여러분 모두에게 희망을드립니다.


android use android : hint = "이름 입력"에서 힌트라고합니다.


@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]);
    }

}

편집 텍스트에 텍스트를 넣고 말한 것처럼 제거하려면 다음을 시도하십시오.

    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("");
                }
            }
        }
    });

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: http://i.stack.imgur.com/juJnt.png


//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


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("");    
}

((EditText) findViewById(R.id.User)).setText("");
((EditText) findViewById(R.id.Password)).setText("");

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

참고URL : https://stackoverflow.com/questions/4175398/how-to-clear-an-edittext-on-click

반응형