Android : Change Typeface of Edit Text for new text that is entered

爱⌒轻易说出口 提交于 2019-12-14 02:48:54

问题


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


来源:https://stackoverflow.com/questions/31365879/android-change-typeface-of-edit-text-for-new-text-that-is-entered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!