2012년 6월 25일 월요일

안드로이드 EditText 입력 할 때마다, 콤마 자동 추가


String strCollectAmount ="";   // --> 입력할때마다 문자가 채워지므로 첨엔 "" 해도 된다.

// EditText 입력 할 때마다, 콤마 자동 추가
final EditText f230_REALMONEY_TD = (EditText) findViewById(R.id.f230_REALMONEY_TD);
f230_REALMONEY_TD.setInputType(InputType.TYPE_CLASS_NUMBER);


f230_REALMONEY_TD.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}


public void onTextChanged(CharSequence s, int start, int before,
int count) {
// 숫자가 추가되었을때에 Comma를 추가해준다.
if (!s.toString().equals(strCollectAmount)) {
// 숫자에 Comma를 추가해주는 메소드 호출
strCollectAmount = Util.makeStringWithComma(s.toString()
.replace(",", ""), true);
f230_REALMONEY_TD.setText(strCollectAmount);
Editable e = f230_REALMONEY_TD.getText();
// 커서의 위치가 현재 입력된 위치의 끝쪽에 가게 해야 한다.
Selection.setSelection(e, strCollectAmount.length());
}
}


public void afterTextChanged(Editable s) {
}
});


/**
* 문자열에 통화적용을 위해 컴마를 표기한다.

* @param string
*            통화적용을 위한 문자열
* @param ignoreZero
*            값이 0일 경우 공백을 리턴한다.
* @return 통화적용이 된 문자열
*/
public static String makeStringWithComma(String string, boolean ignoreZero) {
if (string.length() == 0) {
return "";
}
try {
if (string.indexOf(".") >= 0) {
double value = Double.parseDouble(string);
if (ignoreZero && value == 0) {
return "";
}
DecimalFormat format = new DecimalFormat("###,##0.00");
return format.format(value);
} else {
long value = Long.parseLong(string);
if (ignoreZero && value == 0) {
return "";
}
DecimalFormat format = new DecimalFormat("###,###");
return format.format(value);
}
} catch (Exception e) {
e.printStackTrace();
}
return string;
}

댓글 없음:

댓글 쓰기