Establecer el estilo TextView (negrita o cursiva)


¿Cómo establecer el estilo TextView (negrita o cursiva) con Java y sin usar el diseño XML?

En otras palabras, necesito escribir android:textStyle con Java.

Author: Niranj Patel, 2011-06-01

21 answers

textView.setTypeface(null, Typeface.BOLD_ITALIC);
textView.setTypeface(null, Typeface.BOLD);
textView.setTypeface(null, Typeface.ITALIC);
textView.setTypeface(null, Typeface.NORMAL);

Para mantener el tipo de letra anterior

textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC)
 1600
Author: Tanmay Mandal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-08 03:03:47

Intenta poner esto en TextView para negrita o cursiva

textView.setTypeface(textView.getTypeface(), Typeface.BOLD);
textView.setTypeface(textView.getTypeface(), Typeface.ITALIC);
textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC);
 244
Author: Niranj Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-31 04:44:11

Mediante programación:

Puedes hacerlo programáticamente usando setTypeface():

textView.setTypeface(null, Typeface.NORMAL);      // for Normal Text
textView.setTypeface(null, Typeface.BOLD);        // for Bold only
textView.setTypeface(null, Typeface.ITALIC);      // for Italic
textView.setTypeface(null, Typeface.BOLD_ITALIC); // for Bold and Italic

XML:

Puede configurar directamente en el archivo XML en <TextView /> como:

android:textStyle="normal"
android:textStyle="normal|bold"
android:textStyle="normal|italic"
android:textStyle="bold"
android:textStyle="bold|italic"
 118
Author: Pratik Butani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-15 13:39:20

Tienes dos opciones:

Opción 1 (solo funciona para negrita, cursiva y subrayado):

String s = "<b>Bolded text</b>, <i>italic text</i>, even <u>underlined</u>!"
TextView tv = (TextView)findViewById(R.id.THE_TEXTVIEW_ID);
tv.setText(Html.fromHtml(s));

Opción 2:

Use un Spannable; es más complicado, pero puede modificar dinámicamente los atributos de texto (no solo negrita/cursiva, también colores).

 79
Author: Gabriel Negut,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-30 13:48:08

Mediante programación:

Se puede hacer mediante programación usando el método setTypeface():

A continuación se muestra el código para el tipo de letra predeterminado

textView.setTypeface(null, Typeface.NORMAL);      // for Normal Text
textView.setTypeface(null, Typeface.BOLD);        // for Bold only
textView.setTypeface(null, Typeface.ITALIC);      // for Italic
textView.setTypeface(null, Typeface.BOLD_ITALIC); // for Bold and Italic

Y si desea establecer tipo de letra personalizado :

textView.setTypeface(textView.getTypeface(), Typeface.NORMAL);      // for Normal Text
textView.setTypeface(textView.getTypeface(), Typeface.BOLD);        // for Bold only
textView.setTypeface(textView.getTypeface(), Typeface.ITALIC);      // for Italic
textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC); // for Bold and Italic

XML:

Puede configurar directamente en el archivo XML en <TextView /> de la siguiente manera:

android:textStyle="normal"
android:textStyle="normal|bold"
android:textStyle="normal|italic"
android:textStyle="bold"
android:textStyle="bold|italic"

O puede establecer su fuente fav (de activos). para más información ver enlace

 29
Author: akshay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-06 12:41:23
TextView text = (TextView)findViewById(R.id.THE_TEXTVIEW_ID);

Ahora establece las propiedades textview..

text.setTypeface(null, Typeface.BOLD);  //-- for only bold the text
text.setTypeface(null, Typeface.BOLD_ITALIC);  //-- for  bold & italic the text
text.setTypeface(null, Typeface.ITALIC);  // -- for  italic the text
 12
Author: Akash Thakkar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-30 13:48:20

Simplemente si quieres poner el texto en negrita. escribe esta línea en tu diseño en text view property

android:textStyle="bold"
 11
Author: Hira Khan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-30 13:50:40

Pruebe esto para establecer su estilo TextView por código java

txt1.setTypeface(null,Typeface.BOLD_ITALIC);
 9
Author: Nikhil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-30 13:48:59
TextView text = (TextView)findViewById(R.layout.textName);
text.setTypeface(null,Typeface.BOLD);
 8
Author: Khushi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-21 04:47:11

Sería

yourTextView.setTypeface(null,Typeface.DEFAULT_BOLD);

Y la cursiva debe ser capaz de sustituir Typeface.DEFAULT_BOLD por Typeface.DEFAULT_ITALC.

Hazme saber cómo funciona.

 6
Author: DustinRiley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-30 13:48:47

Use textView.setTypeface(Typeface tf, int style); para establecer la propiedad style de la TextView. Consulte la documentación para desarrolladores para obtener más información.

 5
Author: Dinesh Sharma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-05 09:55:50

Prueba esto:

TextView textview = (TextView)findViewById(R.id.textview_idname);
textview.setTypeface(null,Typeface.BOLD);
 4
Author: Black_shadow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-17 10:21:32

La forma estándar de hacer esto es usar los estilos personalizados. Ex -

En styles.xml añádase lo siguiente.

<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="MyApp.TextAppearance.LoginText">
    <item name="android:textStyle">bold|italic</item>
</style>

Aplique este estilo a su TextView de la siguiente manera.

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    style="@style/MyApp.TextAppearance.LoginText" />
 3
Author: Shivanand Darur,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-30 13:49:27

Ya que quiero usar una fuente personalizada solo la conjunción de varias respuestas funciona para mí. Obviamente los ajustes en mi layout.xml como android:textStlyle="italic" fueron ignorados por AOS. Así que finalmente tuve que hacer lo siguiente: en strings.xml la cadena de destino fue declarada como:

<string name="txt_sign"><i>The information blah blah ...</i></string>

Luego adicionalmente en el código:

TextView textSign = (TextView) findViewById(R.id.txt_sign);
FontHelper.setSomeCustomFont(textSign);
textSign.setTypeface(textSign.getTypeface(), Typeface.ITALIC);

No probé la opción Spannable (que supongo que debe funcionar) pero

textSign.setText(Html.fromHtml(getString(R.string.txt_sign))) 

No tuvo efecto. También si elimino el italic tag de strings.xml dejando el setTypeface() solo tampoco tiene efecto. Difícil Androide...

 1
Author: Stan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-25 09:57:36

Y como se explica aquí Android Developers String Resources si necesita usar parámetros en su recurso de texto con estilo, debe escapar de los corchetes de apertura

<resources>
<string name="welcome_messages">Hello, %1$s! You have &lt;b>%2$d new messages&lt;/b>.</string>
</resources>

Y llamar a formatHtml (string)

Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
CharSequence styledText = Html.fromHtml(text);
 1
Author: Angelo Nodari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-14 15:50:45

Una forma de hacerlo es :

myTextView.setTypeface(null, Typeface.ITALIC);
myTextView.setTypeface(null, Typeface.BOLD_ITALIC);
myTextView.setTypeface(null, Typeface.BOLD);
myTextView.setTypeface(null, Typeface.NORMAL);

Otra opción si desea mantener el tipo de letra anterior y no quiere perder aplicado previamente entonces:

myTextView.setTypeface(textView.getTypeface(), Typeface.NORMAL);      
myTextView.setTypeface(textView.getTypeface(), Typeface.BOLD);        
myTextView.setTypeface(textView.getTypeface(), Typeface.ITALIC);      
myTextView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC); 
 1
Author: param,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-27 00:48:36

Puedes probar así:

<string name="title"><u><b><i>Your Text</i></b></u></string>
 1
Author: Vishal Vaishnav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-31 07:42:11

En mi caso:

1-conjunto de texto

2-establecer el tipo de letra

holder.title.setText(item.nome);
holder.title.setTypeface(null, Typeface.BOLD);
 1
Author: FlipNovid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-28 17:15:59

La mejor manera es definirlo en styles.xml

<style name="common_txt_style_heading" parent="android:style/Widget.TextView">
        <item name="android:textSize">@dimen/common_txtsize_heading</item>
        <item name="android:textColor">@color/color_black</item>
        <item name="android:textStyle">bold|italic</item>
</style>

Y actualizarlo en TextView

  <TextView
     android:id="@+id/txt_userprofile"
     style="@style/common_txt_style_heading"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_centerHorizontal="true"
     android:layout_marginTop="@dimen/margin_small"
     android:text="@string/some_heading" />
 0
Author: Faheem,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-30 13:49:57
AppCompatTextView text =(AppCompatTextView)findViewById(R.layout.appCompatTextView1);
text.setTypeface(null,Typeface.BOLD);

Utilice el método anterior para establecer el tipo de letra mediante programación.

 0
Author: Tulsi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-02 08:48:55

Esto es lo único que funcionó para mí en un OnePlus 5T configurado con la fuente OnePlus Slate™:

textView.setTypeface(Typeface.create(textView.getTypeface(), useBold ? Typeface.BOLD : Typeface.NORMAL));

Otros métodos harían que volviera a Roboto cuando sea NEGRITA o NORMAL.

 0
Author: droid256,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-29 20:57:29