How to Add Multiple Font to Single EditText Mean Each Word have Different Font Based on Run time

Viewed 158

Hi i need to add multiple font to each word enter in edittext , mean every word have different font , i done some of the work with below code .

SpannableStringBuilder SS = new 
SpannableStringBuilder(enterword.getText().toString());
SS.setSpan (new CustomTypefaceSpan("", font2), 0, size , 
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
enterword.setText(SS);

but this one is working when you have manually assign the text . also i attach image enter image description here

1 Answers

It's a bit tricky to do it in an EditText since it's editable. One approach you can take is - add a TextWatcher or onTextChangedListener to your EditText.

Override afterTextChanged of the TextWatcher and add a custom logic such as following.

String[] words = text.split();
SpannableStringBuilder sb = new SpannableStringBuilder();
for (String word in words) {
    SpannableString spanned = new SpannableString(word);
    spanned.setSpan( -- your font span here --);
    sb.append(spanned);
    sb.append(" ");
}

editText.setText(sb);

You have to add your own logic when and how you want to convert it. When you call editText.setText, afterTextChanged will get triggered. You need to take care of that recursion using some flag and handler for callbacks.

You could have something like this.

class FontWatcher(private val editText: EditText) : TextWatcher {
    private val handler = Handler()
    private var locked = false

    private val updateCallback = Runnable {
        locked = true
        // Create your spannable as mentioned above
        editText.setText(sb, TextView.BufferType.EDITABLE)
        editText.setSelection(sb.length)
        locked = false
    }

    override fun afterTextChanged(s: Editable) {
        if (!locked) {
            handler.removeCallbacks(updateCallback)
            handler.postDelayed(updateCallback, 300)
        }
    }
}

This is not optimized, but should help you get started.

Related