-->

[Android / Java]

TextWatcher를 통한 EditText의 입력 변화 이벤트

 

* 목표 : TextWatcher를 통해 EditText의 입력 변화 이벤트를 발생시키자.

 

Android에서 입력 변화 이벤트를 사용하는 경우는 매우 많다. Max Length를 정해 그 이상 입력을 못하게 할 수도 있고 금액을 표시할 때 컴마를 붙이게 할 수도 있다. 

이벤트를 언제 적용할 것인가에 따라 다양하게 나타낼 수 있을 텐데 이번에는 입력과 동시에 이벤트가 발생하는 TextWatcher interface를 이용해 보도록 한다.

package android.text;

/**
 * When an object of this type is attached to an Editable, its methods will
 * be called when the text is changed.
 */
public interface TextWatcher extends NoCopySpan {
    /**
     * This method is called to notify you that, within <code>s</code>,
     * the <code>count</code> characters beginning at <code>start</code>
     * are about to be replaced by new text with length <code>after</code>.
     * It is an error to attempt to make changes to <code>s</code> from
     * this callback.
     */
    public void beforeTextChanged(CharSequence s, int start,
                                  int count, int after);
    /**
     * This method is called to notify you that, within <code>s</code>,
     * the <code>count</code> characters beginning at <code>start</code>
     * have just replaced old text that had length <code>before</code>.
     * It is an error to attempt to make changes to <code>s</code> from
     * this callback.
     */
    public void onTextChanged(CharSequence s, int start, int before, int count);

    /**
     * This method is called to notify you that, somewhere within
     * <code>s</code>, the text has been changed.
     * It is legitimate to make further changes to <code>s</code> from
     * this callback, but be careful not to get yourself into an infinite
     * loop, because any changes you make will cause this method to be
     * called again recursively.
     * (You are not told where the change took place because other
     * afterTextChanged() methods may already have made other changes
     * and invalidated the offsets.  But if you need to know here,
     * you can use {@link Spannable#setSpan} in {@link #onTextChanged}
     * to mark your place and then look up from here where the span
     * ended up.
     */
    public void afterTextChanged(Editable s);
}

TextWatcher는 세 가지 메서드를 Implementation 한다. 텍스트 체인지가 발생하기 전 (beforeTextChanged), 발생 할 때(onTextChanged), 그리고 발생한 후(afterTextChanged). 개발자는 원하는 곳에 이벤트를 발생시킬 수 있다.

전에 만든 컴마 넣기를 이용한 예시는 다음과 같다.. (minggu92.tistory.com/14)

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        EditText TotalAmountEt = findViewById(R.id.etTotalAmount);
      	TotalAmountEt.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) {
				 TotalAmountEt.setText(makeStringComma(s.toString())); //컴마붙이기
            }
        });
  }

  protected String makeStringComma(String inputStr) {    // 천단위 콤마 처리
      if (TextUtils.isEmpty(inputStr))
      return inputStr;

      String str = inputStr.replace(",",""); //기존 컴마 제거
      BigDecimal bigDecimal = new BigDecimal(str);
      DecimalFormat format = new DecimalFormat("###,###"); //포맷팅

      String returnStr = format.format(bigDecimal);
      return returnStr; //리턴
  }

다음 시간에는 이 것들을 이용해 큰 금액의 자동 합산 로직을 만들어보겠다.

 

+ Recent posts