1

I want to have different typefaces for different parts of text in the same Edit Text. I have tried doing this to change Typeface :

Typeface myFont = Typeface.createFromAsset(getAssets(), "droid-sans.ttf");
myEditText.setTypeface(myFont, Typeface.BOLD);

I am using a button to make text BOLD.

But this changes Typeface of the entire text that is already present in the EditText ! I want to keep existing text formatting and change Typeface for the text that will be entered after I click "Bold" button.

pg18
  • 35
  • 5
  • check this out http://stackoverflow.com/questions/13227670/using-custom-font-for-part-of-a-text – Sowmia Sundararajan Jul 12 '15 at 08:37
  • That would not be a solution if we want to change TypeFace at runtime. Typeface should be applied to the text at runtime as user types into EditText – pg18 Jul 12 '15 at 08:49

1 Answers1

0

You are looking for Spannable interface. You can use this to change the font of different part of an EditText or TextView.

This is an example code for you to turn a selected text into ITALIC.

Spannable str = mBodyText.getText(); 
if(mBodyText.getSelectionEnd() > mBodyText.getSelectionStart()) 
  str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC),  
                      mBodyText.getSelectionStart(), mBodyText.getSelectionEnd(),  
                      Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
else
  str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC),
              mBodyText.getSelectionEnd(),
              mBodyText.getSelectionStart(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Aritra Roy
  • 15,355
  • 10
  • 73
  • 107
  • Would you please explain me, how can i use this to change typeface "on the fly". If i press Bold button, text that will be typed after pressing the button should get bold. You are processing selected text. – pg18 Jul 12 '15 at 14:21
  • BTW i figured out the way to do that. Your answer works. Thanks a lot !! – pg18 Jul 13 '15 at 07:28
  • @pg18 consider telling **what you figured out** in the answer or comment ! – Hissaan Ali Jul 18 '19 at 07:59