글자 수를 세어주고 원하는 글자수까지만 입력할 수 있도록 하는 기능을 어떻게 구현할수있을까?
Text를 입력하는 창은 EditText로 만들고 리스너를 달아준다!
EditText inputMessage= findViewById(R.id.inputMessage);
TextWatcher watcher = new TextWatcher() {
public void onTextChanged(CharSequence str, int start, int before, int count) {
//텍스트가 입력될때마다 텍스트 숫자를 세어준다.
byte[] bytes = null;
try {
bytes = str.toString().getBytes("KSC5601");
//KSC5601은 안드로이드에서 한글을 byte로 변환하는 방식이라고 한다.
int strCount = bytes.length;
inputCount.setText(strCount + " / 80바이트");
} catch(UnsupportedEncodingException ex) {
ex.printStackTrace();
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable strEditable) {
//텍스트가 입력된후에 정해진 글자수보다 초과했을때 잘라서 넣어준다.
String str = strEditable.toString();
try {
byte[] strBytes = str.getBytes("KSC5601");
if(strBytes.length > 80) {
strEditable.delete(strEditable.length()-2, strEditable.length()-1);
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
};
inputMessage.addTextChagedListener(watcher);
Editable?
편집가능한 문자열로 EditText 의 기본 Type 입니다.
BufferType.EDITABLE 이며, xml 로 정의시에는 android:bufferType="editable".
API
Editable Editable.insert(int where, CharSequence text) // where 위치에 text 추가
Editable Editable.delete (int st, int en) // st~en 까지 삭제
Editable Editable.append (char text) // 마지막에 text 추가
void Editable.clear () // 다 지우기
Editable Editable.replace (int st, int en, CharSequence text) // st~en 까지를 text로 대체출처: https://aroundck.tistory.com/301 [돼지왕 왕돼지 놀이터]