Android : Change Typeface of Edit Text for new tex

2019-08-09 11:15发布

问题:

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.

回答1:

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);