当我按下屏幕键盘上的返回按钮时,如何检测到在EditText字段中创建换行符。
我不在乎是否需要检查换行符或返回键,但我想通过按键盘上的返回键发送消息。
我已经尝试了一些不同的东西,但我似乎无法让它发挥作用。
如果您想知道,我的EditText对象称为chatInputET
。
提前致谢!
答案 0 :(得分:5)
为您的输入添加侦听器:
chatInputET.addTextChangedListener( new TextWatcher(){
@Override
public void onTextChanged( CharSequence txt, int start, int before, int count ) {
if( -1 != txt.toString().indexOf("\n") ){
doSendMsg();
}
}
} );
答案 1 :(得分:4)
chatInputET.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String string = s.toString();
if (string.length() > 0 && string.charAt(string.length() - 1) == '\n') {
// do stuff
}
}
});
答案 2 :(得分:0)
这就是我想出的。设置editText时,将其放在onCreate中。
editText = (EditText) findViewById(R.id.editText1);
editText.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 string = s.toString();
if (string.length() > 0 && string.charAt(string.length() - 1) == '\n') {
// do stuff
// for me i get the string and write to a usb serial port
String data = editText.getText().toString();
if (usbService != null)
{
// if UsbService was correctly binded, Send data
usbService.write(data.getBytes());
editText.setText("");//i clear it.
}
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
答案 3 :(得分:0)
对于任何想要检测“\n”的多行 EditText 输入 任何地方这是我想出了什么:
editText.addTextChangedListener(object : TextWatcher {
private var oldText = editText.text.toString()
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { }
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { }
override fun afterTextChanged(s: Editable?) {
if (s == null) return
val oldLineBreakCount = oldText.count { it == '\n' }
val newLineBreakCount = s.count { it == '\n' }
if (oldLineBreakCount < newLineBreakCount) {
nestedScroll.smoothScrollBy(0, 64) // Scroll by the line height
}
if (oldLineBreakCount > newLineBreakCount) {
nestedScroll.smoothScrollBy(0, -64)
}
oldText = s.toString()
}
})
答案 4 :(得分:0)
private fun isChangeLigne(s: String?): Boolean{
if (s != null && s.isNotEmpty()) {
if (s[s.length - 1] == '\n') {
return true
}
}
return false
}
此 kotlin 函数可用于以文本字符串作为参数的 onTextChanged 回调。另一种解决方案是使用 editText.lineCount 属性。您可以使用以下代码检查行号:
var lineNumber = editText.lineCount
// in onTextChange callack
if(lineNumber!=editText.lineCount){
// detect line change
}