我的应用程序中有一个 EditText 字段,用于显示人的身高。如何格式化它以使其看起来像说 5'9"?当一个人键入 5 时,应用程序应该自己添加 ',当一个人键入 9 时,它应该添加"。我怎么做?谢谢你。
问问题
1950 次
2 回答
2
用这个:
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());
}
于 2012-09-27T18:21:52.867 回答
0
使用这个:删除“'”。
mBinding.edtHeight.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL) {
if (mBinding.edtHeight.getText().length() == 2) {
mBinding.edtHeight.setText("");
}
}
return false;
}
});
于 2018-01-02T12:21:38.683 回答