2

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!

petehallw
  • 1,014
  • 6
  • 21
  • 49

2 Answers2

3

You can do it like this:

String html = "This is a <i>Text</i>.";
editText.setText(Html.fromHtml(html));
Ahmad
  • 69,608
  • 17
  • 111
  • 137
  • 1
    to add to the above answer http://commonsware.com/blog/Android/2010/05/26/html-tags-supported-by-textview.html. list of html tags supported. – Raghunandan Jul 09 '13 at 17:49
  • Supposing I need to do this for variables though? For example: String ref = variable+"." – petehallw Jul 09 '13 at 17:49
  • Raghunandan: thanks for the addition :) Petehallw: you can concatenate the variable on to the string: "" + var + "". – Ahmad Jul 09 '13 at 17:53
  • I appreciate the answers thanks, but the output from this was: 'blahblah'. Am I missing something? – petehallw Jul 09 '13 at 17:59
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

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • Ok but what if my string is made as follows and I only want variable1 to be in italics e.g. String s = variable1+", "+variable2+"." ? – petehallw Jul 09 '13 at 17:55
  • @petehallw you can apply styling only to the variable 1 not a problem. in the above example only hello is in italics. you can also split by the string by space apply span to individual words. I can't find the source but i have answered a similar question before on so long back – Raghunandan Jul 09 '13 at 17:56
  • Ok thank you I will have to look into the parameters for setSpan()! – petehallw Jul 09 '13 at 18:02