我的应用程序中有一个EditText字段,用于显示人的身高。我如何格式化它使其看起来像5'9“?当一个人键入5时,应用程序应自行添加',而当一个人键入9时应添加”。我怎么做?谢谢。
最佳答案
用这个:
public class TextWatcherActivity extends Activity {
EditText e;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
e = (EditText) findViewById(R.id.editText1);
e.addTextChangedListener(new CustomTextWatcher(e));
}
}
class CustomTextWatcher implements TextWatcher {
private EditText mEditText;
public CustomTextWatcher(EditText e) {
mEditText = e;
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void afterTextChanged(Editable s) {
int count = s.length();
String str = s.toString();
if (count == 1) {
str = str + "'";
} else if (count == 2) {
return;
} else if (count == 3) {
str = str + "\"";
} else if (count >= 4) {
return;
}
mEditText.setText(str);
mEditText.setSelection(mEditText.getText().length());
}
}
编辑:
如果用户可以在
'
和"
之间插入一个,两个或多个数字,则可以在上述代码中更改afterTextChanged
,如下所示:public void afterTextChanged(Editable s) {
int count = s.length();
String str = s.toString();
if (count == 1) {
str = str + "'";
} else if (count == 3) {
str = str + "\"";
} else if ((count > 4) && (str.charAt(str.length() - 1) != '\"') ){
str = str.substring(0, str.length() - 2) + str.charAt(str.length() - 1)
+ "\"";
} else {
return;
}
mEditText.setText(str);
mEditText.setSelection(mEditText.getText().length());
}