Reputation: 21
I have to implement textedit where last three chars are bold. I have 3 specific situactions:
so I implement it with html that I put into textedit, to implement this 3 situations I using function doOnTextChanged, but the device is specific scanner and when I use any method from TextWatcher the one important functionality from scanner device stop working.
The functionality is after scan barcode system android return Keycode_ENTER (onKeyListener).
I need to find something like TextWatcher to get dynamically what user types in textedit.
I tried: 1)Don't setText from WatchText object. 2)WatchText update livedata variable and execute settext in observer 3) I cant manually execute keycode_Enter! I have to know if value is scanned
Upvotes: 1
Views: 229
Reputation: 6264
You could be to use the addTextChangedListener
method instead of the TextWatcher
interface to listen for changes in the text editor.
Here's an example code snippet to get you started:
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);
}
}
}
Then, to use this custom TextWatcher
class in your text editor, you can register it with the addTextChangedListener
method like this:
EditText editText = findViewById(R.id.editText);
CustomTextWatcher customTextWatcher = new CustomTextWatcher(editText);
editText.addTextChangedListener(customTextWatcher);
Upvotes: 0