http://www.masterqna.com/android/20262/%EC%97%90%EB%94%94%ED%8A%B8-%ED%85%8D%EC%8A%A4%ED%8A%B8-%EC%9E%85%EB%A0%A5%ED%95%9C-%EA%B8%80%EC%9E%90-%EC%88%98-%ED%85%8D%EC%8A%A4%ED%8A%B8%EB%B7%B0%EB%A1%9C-%EC%B6%9C%EB%A0%A5%ED%95%98%EA%B8%B0-%EC%A7%88%EB%AC%B8%EC%9E%85%EB%8B%88%EB%8B%A4
if (Strings.isNullOrEmpty(string)) { return 0; }
Strings << 이건 google guava 라이브러리에 있는 스트링 Null or Empty 검사입니다.
string == null || “”.equals(string) 과 같은 메서드죠…
그리고 제가 드린 static int getLength 메서드는 글자수를 바이트로 계산해야하는 경우에 사용하는 메서드 입니다.
바이트 계산이 필요없다면 그냥
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
int textLength = s.toString().length();
}
이렇게 얻으시면 되구요.
필요하다면
int textBytes = getLength(s.toString());
이렇게 하시면 됩니다.
package location.androidtown.org.mydoit_chap01_2; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class TextChangeListener extends AppCompatActivity { EditText editText; TextView textCount; Button transButton, closeBtn; int count2=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_text_change_listener); editText =(EditText)findViewById(R.id.edit_text); textCount=(TextView)findViewById(R.id.textCount); transButton =(Button)findViewById(R.id.btnTrans); closeBtn=(Button)findViewById(R.id.btnClose); transButton.setOnClickListener(listener); closeBtn.setOnClickListener(listener); editText.addTextChangedListener(cWatcher); // editText.setFilters(new InputFilter[80]); } View.OnClickListener listener =new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()){ case R.id.btnTrans: Toast.makeText(getApplicationContext(), editText.getText().toString(), Toast.LENGTH_SHORT).show(); break; case R.id.btnClose: break; } } }; TextWatcher cWatcher = new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { count2=getLength(s.toString()); textCount.setText(String.valueOf(count2)); // Toast.makeText(getApplicationContext(), String.valueOf(count), Toast.LENGTH_SHORT).show(); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }; public static int getLength(String string) { if (string == null || "".equals(string) ) { return 0; } int length = string.length(); int charLength = 0; for (int i = 0; i < length; i++) { charLength += string.codePointAt(i) > 0x00ff ? 2 : 1; } return charLength; } }
댓글 ( 4)
댓글 남기기