2

I want to make animal.getScientificName as Italics(code below). I'm using a List View and setting the text in the listview. I wan't only part of the Text view to be in Italics, Is there anyway I can accomplish this. I have attached part of the code below, Thanks for your help.

String[] listNames;

listNames[ i ] = animal.getName().toUpperCase().replaceAll( "_" , " " ) + " \n\n" + "+animal.getScientificName()+"; 


array_sort = new ArrayList( Arrays.asList( listNames) ); 
tv.setText( array_sort.get( position ) );
Richard Le Mesurier
  • 29,432
  • 22
  • 140
  • 255
user3458008
  • 329
  • 3
  • 9
  • 21

3 Answers3

3

You can accomplish this using spans on your text (to expand here on the correct answer in comment by Georgian Benatos).

Here is a related question, and the answers show you exactly how to do this:

Specifically some sample code in the answer provided by Raghunandan

String title="My Custom Text!";  
TextView tv = (TextView) findViewById(R.id.some_id);
SpannableString ss1=  new SpannableString(title);
ss1.setSpan(new StyleSpan(Typeface.ITALIC), 0, ss1.length(), 0);
ss1.setSpan(new RelativeSizeSpan(2f), 0, ss1.length, 0); 
tv.setText(ss1);

Spans are a very useful feature - they can be used for various common text styles:

  • italics
  • bold
  • underline
  • bullets

To have a look at the wide range of spans available, take a look at the Android developers page for the android.text.style package:

Community
  • 1
  • 1
Richard Le Mesurier
  • 29,432
  • 22
  • 140
  • 255
2

use Html.fromHtml:

listNames[ i ] = animal.getName().toUpperCase().replaceAll( "_" , " " ) + " \n\n" + "<em>+animal.getScientificName()+</em>"; 


array_sort = new ArrayList( Arrays.asList( listNames) ); 
tv.setText(Html.fromHtml(array_sort.get( position ) ));

for more info, refer this

Community
  • 1
  • 1
user3487063
  • 3,672
  • 1
  • 17
  • 24
0

I would recommend using two TextViews, because it is impossible to have two different text-styles in one TextView.

Just place them both under each other, and assign the correct String value to the TextView.

tv1.setText(animal.getName().toUpperCase().replaceAll( "_" , " " );
tv2.setText(animal.getScientificName();

And for example, you can use this layout in your ListView item:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/tv1" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/tv2"
        android:textStyle="italic" />

</LinearLayout>
Hookah_Smoka
  • 374
  • 1
  • 2