我已經實現了一個撥號盤,我不想允許用戶在edittext的左邊位置以外插入「+」。如何允許插入一個字符只有edittext的最左邊位置android
2
A
回答
2
您應該根據您的要求使用InputFilter
。試試下面的代碼:
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (source.charAt(i) == '+' && i!=start) {
Toast.makeText(getApplicationContext(),"Invalid Input",Toast.LENGTH_SHORT).show();
return "";
}
}
return null;
}
};
editText.setFilters(new InputFilter[] { filter });
希望這會有所幫助。
0
您大概可以利用TextWatcher
。如下面的代碼的東西應該服務宗旨:
txtNumbers.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) {
}
@Override
public void afterTextChanged(Editable s) {
// Do the magic here
int positionOfPlus = txtNumbers.getText().toString().indexOf("+");
if (positionOfPlus != -1 && positionOfPlus != 0) {
txtNumbers.setText("+" + txtNumbers.getText().toString().replace("+", ""));
}
}
});
欲瞭解更多有關TextWatcher
,讀到這裏:TextWatcher | Android Developers
0
這裏是代碼片段這樣的伎倆:
editText.addTextChangedListener(新TextWatcher(){
@Override
public void afterTextChanged(Editable s) {}
@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
// here you can check for '+' sign, and then you can remove additional '=' sign from it.
}
});
希望這會幫助你。
相關問題
- 1. EditText只允許8個字符
- 2. 只允許兩位小數輸入EDITTEXT
- 3. 只允許EditText中的字符串
- 4. 只去掉字符串中最左邊的字母,只有左邊的字母
- 5. 輸入允許數字和只有一個字母/符號
- 6. 只允許8個字符
- 7. 離子輸入只允許一次輸入一個字符
- 8. 只允許一個查詢字符串
- 9. 如何只允許Android的
- 10. Android只允許通過矩形的一邊進入
- 11. 在字符串的第一個和最後一個位置插入字符
- 12. 只允許輸入一個字符的實例C#
- 13. 只允許數字字符
- 14. 得到最後一個字符在插入符號前插入位置
- 15. EditText只允許字母,所有語言的數字
- 16. 如何只允許-ZA-Z字符
- 17. 如何只允許輸入字母?
- 18. 如何使輸入只允許輸入兩個小數位數?
- 19. 允許EditText中的特定字符並阻止所有其他字符Android
- 20. 如何驗證QlineEdit以允許只寫一個字符串或允許寫入數字
- 21. 如何只允許大寫字母輸入到一個變量
- 22. 只允許ASCII字符VBA
- 23. 只允許小寫字符
- 24. 只允許某些字符
- 25. 如何只允許數字?
- 26. 只允許輸入字母
- 27. 只允許數字輸入
- 28. mongodb錯誤驗證設置:只允許一個位置參數
- 29. 只允許一些字符與grep?
- 30. 只允許輸入一次數字
你的答案是偉大的,但需要返回 source.toString()子(0,source.length() - 1) 而不是 「」 – Zia
這只是你的'EditText'過濾器。如果用戶將其他地方放在其他地方而不是開始,這將返回「」。如果用戶正確地放置了'+',你可以稍後編輯'edittext.getText()。toString()。substring(0,source.length() - 1)'。 – tahsinRupam