How do you display part of text field in italics in android?

烈酒焚心 提交于 2019-12-24 03:48:16

问题


I am developing an Android app which takes some data from text fields entered by the user, and outputs a single string in a new text field based on this data. Simple enough, however I need parts of the string to be in italics.

I have found out how to make the entire text field display in italics (shown below) but how about choosing only specific variables which make up the string to be shown in italics?

public class RefGenActivity extends Activity {

private EditText reftext;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_refgen);
reftext = (EditText) findViewById(R.id.editText1);      
reftext.setTypeface(null, Typeface.ITALIC); //SET TO ITALICS
reftext.setText(getRef());
}

Any help would be much appreciated!


回答1:


You can do it like this:

String html = "This is a <i>Text</i>.";
editText.setText(Html.fromHtml(html));



回答2:


You can use a Spannable String

String s= "Hello Everyone";
  SpannableString ss1=  new SpannableString(s);
  ss1.setSpan(new RelativeSizeSpan(2f), 0,5, 0);
  ss1.setSpan(new ForegroundColorSpan(Color.RED), 0, 5, 0); 
  ss1.setSpan(new StyleSpan(Typeface.ITALIC), 0, 5, 0); 
  ss1.setSpan(new StyleSpan(Typeface.BOLD), 0, ss1.length(), 0);
  ss1.setSpan(new ForegroundColorSpan(Color.RED), 0, ss1.length(), 0); 
  editText.append(ss1); 

For more styling

http://www.chrisumbel.com/article/android_textview_rich_text_spannablestring



来源:https://stackoverflow.com/questions/17554783/how-do-you-display-part-of-text-field-in-italics-in-android

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