¿Cómo establecer el estilo de fuente en negrita, cursiva y subrayado en un Android TextView?


450

Quiero que TextViewel contenido de a sea negrita, cursiva y subrayado. Intenté el siguiente código y funciona, pero no subraya.

<Textview android:textStyle="bold|italic" ..

¿Cómo lo hago? ¿Alguna idea rápida?


¿Funciona configurar solo uno de ellos?
— falstro

sí, funciona bien, también quiero hacerlo en línea.
— d-man

66
textView.setPaintFlags (Paint.UNDERLINE_TEXT_FLAG);
— bCliks el

15
tv.setTypeface(null, Typeface.BOLD_ITALIC);

3
4 formas de hacer Android TextView Bold Creo que deberías leer este artículo.
— c49

Respuestas:


279

No sé sobre subrayado, pero para negrita y cursiva sí "bolditalic". No hay mención de subrayado aquí: http://developer.android.com/reference/android/widget/TextView.html#attr_android:textStyle

Tenga en cuenta que para usar lo mencionado bolditalicnecesita hacerlo, y cito de esa página

Debe ser uno o más (separados por '|') de los siguientes valores constantes.

entonces usarías bold|italic

Puede verificar esta pregunta para subrayar: ¿Puedo subrayar texto en un diseño de Android?


48
por debajo de la línea .. textView.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
— bCliks

1
@bala, tenga en cuenta que su solución siempre subraya el texto completo, por lo que no es factible en los casos en que se desea subrayar solo una parte de él.
— Giulio Piancastelli

362

Esto debería hacer que su TextView esté en negrita , subrayado y en cursiva al mismo tiempo.

strings.xml

<resources>
    <string name="register"><u><b><i>Copyright</i></b></u></string>
</resources>

Para establecer esta cadena en su TextView, haga esto en su main.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="@string/register" />

o en JAVA ,

TextView textView = new TextView(this);
textView.setText(R.string.register);

A veces, el enfoque anterior no será útil cuando tenga que usar Texto dinámico. Entonces, en ese caso, SpannableString entra en acción.

String tempString="Copyright";
TextView text=(TextView)findViewById(R.id.text);
SpannableString spanString = new SpannableString(tempString);
spanString.setSpan(new UnderlineSpan(), 0, spanString.length(), 0);
spanString.setSpan(new StyleSpan(Typeface.BOLD), 0, spanString.length(), 0);
spanString.setSpan(new StyleSpan(Typeface.ITALIC), 0, spanString.length(), 0);
text.setText(spanString);

SALIDA

ingrese la descripción de la imagen aquí


3
Lo revisé en 2.1. Así que al menos debería funcionar desde 2.1 y superiores
— Andro Selva

Puede considerar usarnew StyleSpan(Typeface.BOLD_ITALIC)
— Cheok Yan Cheng

¿Por qué no funciona en una cadena concatenada dinámica? Está conectado que aparecieron algunos números ...
— AuBee

152

O simplemente así en Kotlin:

val tv = findViewById(R.id.textViewOne) as TextView
tv.setTypeface(null, Typeface.BOLD_ITALIC)
// OR
tv.setTypeface(null, Typeface.BOLD or Typeface.ITALIC)
// OR
tv.setTypeface(null, Typeface.BOLD)
// OR
tv.setTypeface(null, Typeface.ITALIC)
// AND
tv.paintFlags = tv.paintFlags or Paint.UNDERLINE_TEXT_FLAG

O en Java:

TextView tv = (TextView)findViewById(R.id.textViewOne);
tv.setTypeface(null, Typeface.BOLD_ITALIC);
// OR
tv.setTypeface(null, Typeface.BOLD|Typeface.ITALIC);
// OR
tv.setTypeface(null, Typeface.BOLD);
// OR
tv.setTypeface(null, Typeface.ITALIC);
// AND
tv.setPaintFlags(tv.getPaintFlags()|Paint.UNDERLINE_TEXT_FLAG);

Mantenlo simple y en una línea :)


1
Al insertar el paquete kotlinx.android.synthetic para la vista con la que está trabajando, findViewByID no es necesario en Kotlin, haciendo que cada una de las líneas setTypeface: textViewOne.setTypeface (...)
— cren90

es paintFlagsnecesario? Funciona sin eso
— Prabs

75

Para negrita y cursiva, todo lo que está haciendo es correcto para subrayar, use el siguiente código

HolaAndroid.java

 package com.example.helloandroid;

 import android.app.Activity;
 import android.os.Bundle;
 import android.text.SpannableString;
 import android.text.style.UnderlineSpan;
import android.widget.TextView;

public class HelloAndroid extends Activity {
TextView textview;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    textview = (TextView)findViewById(R.id.textview);
    SpannableString content = new SpannableString(getText(R.string.hello));
    content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
    textview.setText(content);
}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="@string/hello"
android:textStyle="bold|italic"/>

string.xml

<?xml version="1.0" encoding="utf-8"?>
 <resources>
  <string name="hello">Hello World, HelloAndroid!</string>
  <string name="app_name">Hello, Android</string>
</resources>

Para eliminar el underlinevalor nulo del pase en lugar de lo new UnderlineSpan()siguiente content.setSpan(null, 0, content.length(), 0);
— Sami Eltamawy

47

Esta es una manera fácil de agregar un subrayado, manteniendo otras configuraciones:

textView.setPaintFlags(textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

Tenga en cuenta que esta solución siempre subraya el texto completo, por lo que no es factible en los casos en que se desea subrayar solo una parte de él.
— Giulio Piancastelli

42

Programáticamente:

Puede hacerlo mediante programación utilizando el método setTypeface ():

A continuación se muestra el código de 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 quieres configurar Tipografía personalizada:

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 establecer directamente en un archivo XML en:

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

¿Cómo puedo cambiar la familia de fuentes usando setTypeface también aplicar negrita, cursiva, subrayado?
— Príncipe


23

Si está leyendo ese texto desde un archivo o desde la red.

Puede lograrlo agregando etiquetas HTML a su texto como se menciona

This text is <i>italic</i> and <b>bold</b>
and <u>underlined</u> <b><i><u>bolditalicunderlined</u></b></i>

y luego puede usar la clase HTML que procesa cadenas HTML en texto con estilo visualizable.

// textString is the String after you retrieve it from the file
textView.setText(Html.fromHtml(textString));

El método fromHtml (String) quedó en desuso en el nivel 24 de API. Más discusión aquí: stackoverflow.com/questions/37904739/…
— Pavel Biryukov

20

Sin comillas me funciona:

<item name="android:textStyle">bold|italic</item>



3

Puede lograrlo fácilmente usando Kotlin buildSpannedString{}bajo su core-ktxdependencia.

val formattedString = buildSpannedString {
    append("Regular")
    bold { append("Bold") }
    italic { append("Italic") }
    underline { append("Underline") }
    bold { italic {append("Bold Italic")} }
}

textView.text = formattedString

Esta debería ser la respuesta aceptada al 100%
— sachadso
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.