[英]Place # symbol after blank space while typing in an EditText
我在一個項目中工作,在該項目中我們只需要添加主題標簽,例如#mytag1 #mytag2 等。我希望每當用戶按下空格按鈕時,它都會在 spcae 后自動添加 #。 這是我嘗試過的(但做那個應用程序變得沒有響應)。
tagsEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String a = s.toString().replace(" ", " #");
tagsEt.setText(a);
}
@Override
public void afterTextChanged(Editable s) {
}
});
這是解決方案。 我已經對代碼的大部分部分進行了注釋,因此您可以輕松理解。
/*To place a # symbol after a blank space while typing in tags input field*/
InputFilter inputFilter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
StringBuilder builder = new StringBuilder();
for (int i = start; i < end; i++) {
//get currently typed character
char currentChar = source.charAt(i);
//check if it typed character was a blank space or not
if (currentChar == ' ') {
//typed character is a blank space, add space and #
builder.append(currentChar);
builder.append('#');
} else {
//typed character is not a blank space, add the character as it is
builder.append(currentChar);
}
}
return builder.toString();
}
};
tagsEt.setFilters(new InputFilter[]{inputFilter});
我認為你應該修剪整個文本並檢查最后一個字符,就像這樣
if (s.toString().trim().charAt(s.length() - 1) == ' ') {
// do the job here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.