2011-01-07 30 views
334

Quiero hacer un contenido de TextView en negrita, cursiva y subrayado. Probé el siguiente código y funciona, pero no subraya.¿Cómo establecer el estilo de fuente en negrita, cursiva y subrayado en una vista de texto de Android?

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

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

+0

Funciona para configurar sólo uno de ellos? – falstro

+0

si funciona bien también quiero hacerlo en línea. –

+5

textView.setPaintFlags (Paint.UNDERLINE_TEXT_FLAG); – bCliks

Respuesta

211

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

Eso sí que usar el citado bolditalic es necesario, y cito de esa página

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

por lo que tendría que utilizar bold|italic

Usted puede comprobar esta pregunta para subrayado: Can I underline text in an android layout?

+43

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 uno quiere subrayar solo una parte de él. –

62

Para negrita y cursiva lo que está haciendo es correcto para el uso de subrayado siguiente código

HelloAndroid. 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> 
+0

Para eliminar el valor 'Pase subrayado' Valor nulo en lugar del 'nuevo UnderlineSpan()' como 'content.setSpan (null, 0, content.length(), 0);' –

332

Esto hará que sus TextView negrita, subrayado y cursiva al mismo tiempo.

strings.xml

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

Para establecer esta cadena a la Vista de Texto, hacer 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

enter image description here

+0

¿Funciona esto para TODOS los niveles API? – kape123

+3

Lo revisé en 2.1.Por lo tanto, al menos debería funcionar desde 2.1 y por encima de –

+3

La solución SpannableString no funciona. – Phillip

18

sin comillas funciona para mí:

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

Esta es una manera fácil de agregar un subrayado, manteniendo al mismo tiempo otros ajustes:

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

Tenga en cuenta que esta solución siempre subraya el texto completo, por lo que no es factible en los casos en que uno quiera subrayar solo una parte. –

108

O simplemente como esto 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); 

que sea sencillo y en una línea :)

+0

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

4
style="?android:attr/listSeparatorTextViewStyle 
  • al hacer este estilo , puede lograr el subrayado
16

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

Puede lograrlo mediante la adición de etiquetas HTML para el texto, como se ha mencionado

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

y entonces usted puede utilizar la clase HTML que procesa las cadenas HTML en texto con estilo visualizable.

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

¡Gracias! esto es muy conveniente para mí que hacerlo en archivos xml. – mboy

+0

fromHtml (String) método se desaprobó en API nivel 24 Más discusión aquí: https://stackoverflow.com/questions/37904739/html-fromhtml-deprecated-in-android-n –

29

Programmatialy:

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

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 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:

Se puede establecer directamente en el archivo XML en como:

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