android - 当在键盘上按下特定字符时,我可以切换到另一个 EditText 吗?
问题描述
我的应用中有 3 个 EditText。我想这样做,如果用户在 EditText1 中输入并按空格键,他将被“发送”到第二个 EditText,从 EditText2 到 EditText3 也是如此。但是,当在 EditTexts 中给出一个空格时,它不应该出现。
这可能吗?我该怎么做?
解决方案
Yes sure you can use TextWatcher
Java version
et1.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s != null && s.endsWith("Your_special_char")){
yourDesiredEditText.requestFocus();
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void afterTextChanged(Editable s) {}
});
Kotlin version
et1.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(p0: Editable?) {
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
if (p0?.endsWith("Your_special_char") == true){//it will eliminate nullability (trick)
yourDesiredEditText.requestFocus()
}
}
})
EDIT
the only issue is I have with this is you end up with a ton of code in each event.
Ok I will provide a clean and neat solution using Kotlin extension functions
fun EditText.forwardFocusOnSpecialCharEntered(targetEditText: EditText) {
this.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(p0: Editable?) {}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
if (p0?.endsWith(" ") == true) targetEditText.requestFocus()
}
})
}
Usage
firstEditText.forwardFocusOnSpecialCharEntered(secondEditText)
secondEditText.forwardFocusOnSpecialCharEntered(thirdEditText)
thirdEditText.forwardFocusOnSpecialCharEntered(firstEditText)
Now using one line of code you can achieve your goal as well as your code stays clean and readable
推荐阅读
- c# - 使用自定义 MsBuild 任务 Nuget 发送依赖项或 Nuget 引用
- python - 如何在我的计算机中从自定义 Python 中提取 Palantir-foundry 数据
- asp.net - 我应该如何扩展我的 ASP .NET Core Api 以支持基于条件的推送通知?
- python - replace() 删除整个单词而不是字符
- javascript - 在移动设备上时内容不显示?我的媒体查询似乎不是问题
- python - Sympy:AttributeError:将多项式乘以复数常数
- php - 如何使用 Vue 循环对象,类似于 PHP?
- c# - 如何修复我的 c# 控制台网络框架 PacMan 游戏?
- javascript - Applescript 代码的等效 Javascript 代码
- r - 使用 R 使用 jsonlite 将数据帧转换为 JSON 对象