我必须实现文本编辑,其中最后三个字符是粗体。我有 3 个具体情况:
所以我用我放入 textedit 的 html 来实现它,为了实现这 3 种情况,我使用函数 doOnTextChanged,但是设备是特定的扫描仪,当我使用 TextWatcher 的任何方法时,扫描仪设备的一个重要功能停止工作。
功能是在扫描条码系统android return Keycode_ENTER (onKeyListener)之后。
我需要找到类似 TextWatcher 的东西来动态获取用户在 textedit 中输入的内容。
我试过: 1)不要从 WatchText 对象中设置文本。 2)WatchText更新livedata变量并在observer中执行settext 3)我不能手动执行keycode_Enter!我必须知道价值是否被扫描
您可以使用
addTextChangedListener
方法而不是 TextWatcher
接口来监听文本编辑器中的更改。
这里有一个示例代码片段可以帮助您入门:
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.widget.EditText;
import androidx.core.text.HtmlCompat;
import androidx.core.widget.TextViewCompat;
import org.jetbrains.annotations.NotNull;
public class CustomTextWatcher extends SimpleTextWatcher {
private EditText editText;
private String lastThreeChars = "";
public CustomTextWatcher(EditText editText) {
this.editText = editText;
}
@Override
public void afterTextChanged(Editable s) {
// get the current text entered by the user
String text = s.toString();
// check if the text is scanned or entered manually
boolean isScanned = /* your logic to detect if the value is scanned */
// update the last three characters with bold formatting
if (text.length() >= 3) {
lastThreeChars = text.substring(text.length() - 3);
String formattedText = text.substring(0, text.length() - 3) +
"<b>" + lastThreeChars + "</b>";
editText.setText(Html.fromHtml(formattedText));
}
// if the value is scanned, manually execute the ENTER key event
if (isScanned) {
KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER);
editText.onKeyDown(KeyEvent.KEYCODE_ENTER, event);
}
}
}
然后,要在您的文本编辑器中使用这个自定义的
TextWatcher
类,您可以使用像这样的addTextChangedListener
方法注册它:
EditText editText = findViewById(R.id.editText);
CustomTextWatcher customTextWatcher = new CustomTextWatcher(editText);
editText.addTextChangedListener(customTextWatcher);