[Android ,안드로이드]TextWatcher,천단위

2013. 3. 7. 13:31Mobile/Android



반응형
안드로이드 EditText 입력 or 지울때 3자리숫자마다 컴마 찍을수 있고 지울수 있다 퍼갈때는 출처를 밝혀주세요~ 만드느라 고생함 ㅠㅠ
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    EditText e = new EditText(this);
    e.addTextChangedListener(new CustomTextWatcher(e));
}


package ggari.com;
import java.text.DecimalFormat;

import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.widget.EditText;

public class CustomTextWathcer implements TextWatcher {
	@SuppressWarnings("unused")
	private EditText mEditText;
	String strAmount = ""; // 임시저장값 (콤마)

	public CustomTextWathcer(EditText e) {
		mEditText = e;
	}

	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub

	}

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

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		if (!s.toString().equals(strAmount)) { // StackOverflow를 막기위해,
			strAmount = makeStringComma(s.toString().replace(",", ""));
			mEditText.setText(strAmount);
			Editable e = mEditText.getText();
			Selection.setSelection(e, strAmount.length());
		}
	}

	protected String makeStringComma(String str) {
		if (str.length() == 0)
			return "";
		long value = Long.parseLong(str);
		DecimalFormat format = new DecimalFormat("###,###");
		return format.format(value);
	}

}
반응형