Parole in grassetto in una stringa di strings.xml in Android


115

Ho un testo lungo in una delle stringhe in strings.xml. Voglio rendere grassetto e cambiare il colore di alcune parole in quel testo.

Come posso farlo?


Puoi essere un po 'più specifico in termini di ciò che stai cercando di ottenere in generale?
— Brian

Risposte:


192

Potresti fondamentalmente usare tag html nella tua risorsa stringa come:

<resource>
    <string name="styled_welcome_message">We are <b><i>so</i></b> glad to see you.</string>
</resources>

E usa Html.fromHtml o usa spannable, controlla il link che ho pubblicato.

Vecchia domanda simile: è possibile avere più stili all'interno di un TextView?


16
Inoltre, a seconda di come si utilizza la stringa della risorsa, potrebbe essere necessario inserire i tag grassetto / corsivo in un blocco CDATA in modo che non vengano analizzati fino a quando non viene utilizzato da Html.fromHtml(): ... <![CDATA[<b><i>so</i></b>]]>...
— dule

133
Per chiunque altro abbia trovato la documentazione ufficiale di Android un po 'troppo vaga su questo: se usi tag come <b> nella tua risorsa di stringa, assicurati di recuperarlo usando getText(R.string.whatever)piuttosto chegetString(R.string.whatever)
— andygeers

1
non dovrebbe essere nameinvece di id?
— Hendra Anggrian

4
Quindi non c'è bisogno di Html.fromHtmlo Spannable. Usa getText(R.string.whatever)come menzionato @andygeers.
— Alaa M.

1
@andygeers Cosa possiamo fare per una stringa come "My name is <b>% s </b>" che non può utilizzare getText poiché accetta solo un singolo parametro?
— Taylor,

45

Usa tag html all'interno delle risorse di stringa: -

<resources>
<string name="string_resource_name"><![CDATA[<b> Your text </b>]]> </string>
</resources>

E ottieni testo in grassetto da risorse stringa come: -

private Spanned getSpannedText(String text) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return Html.fromHtml(text, Html.FROM_HTML_MODE_COMPACT);
        } else {
            return Html.fromHtml(text);
        }
    }


 String s = format(context.getResources().getString(R.string.string_resource_name));
 textView.setText(getSpannedText(s));

è la risposta migliore e funziona totalmente per le persone che usano @BindingAdapter. Grazie Fratello.
— Sup.Ia

44

Come ha detto David Olsson, puoi usare HTML nelle tue risorse di stringa:

<resource>
    <string name="my_string">A string with <i>actual</i> <b>formatting</b>!</string>
</resources>

Quindi se usi getText(R.string.my_string)piuttosto che getString(R.string.my_string)ricevi un CharSequenceinvece di un Stringche contiene la formattazione incorporata.


getText restituisce CharSequence non a Spannable
— Tigran Babajanyan

1
E se la tua stringa è una quantità a cui devi aggiungere un numero?
— Taylor,

getText non consente di utilizzare segnaposto
— Vincent_Paing

11

In kotlin, puoi creare funzioni di estensioni sulle risorse (attività | frammenti | contesto) che convertiranno la tua stringa in un intervallo html

per esempio

fun Resources.getHtmlSpannedString(@StringRes id: Int): Spanned = getString(id).toHtmlSpan()

fun Resources.getHtmlSpannedString(@StringRes id: Int, vararg formatArgs: Any): Spanned = getString(id, *formatArgs).toHtmlSpan()

fun Resources.getQuantityHtmlSpannedString(@PluralsRes id: Int, quantity: Int): Spanned = getQuantityString(id, quantity).toHtmlSpan()

fun Resources.getQuantityHtmlSpannedString(@PluralsRes id: Int, quantity: Int, vararg formatArgs: Any): Spanned = getQuantityString(id, quantity, *formatArgs).toHtmlSpan()

fun String.toHtmlSpan(): Spanned = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    Html.fromHtml(this, Html.FROM_HTML_MODE_LEGACY)
} else {
    Html.fromHtml(this)
}

uso

//your strings.xml
<string name="greeting"><![CDATA[<b>Hello %s!</b><br>]]>This is newline</string>

//in your fragment or activity
resources.getHtmlSpannedString(R.string.greeting, "World")

MODIFICA ancora più estensioni

fun Context.getHtmlSpannedString(@StringRes id: Int): Spanned = getString(id).toHtmlSpan()

fun Context.getHtmlSpannedString(@StringRes id: Int, vararg formatArgs: Any): Spanned = getString(id, *formatArgs).toHtmlSpan()

fun Context.getQuantityHtmlSpannedString(@PluralsRes id: Int, quantity: Int): Spanned = resources.getQuantityString(id, quantity).toHtmlSpan()

fun Context.getQuantityHtmlSpannedString(@PluralsRes id: Int, quantity: Int, vararg formatArgs: Any): Spanned = resources.getQuantityString(id, quantity, *formatArgs).toHtmlSpan()


fun Activity.getHtmlSpannedString(@StringRes id: Int): Spanned = getString(id).toHtmlSpan()

fun Activity.getHtmlSpannedString(@StringRes id: Int, vararg formatArgs: Any): Spanned = getString(id, *formatArgs).toHtmlSpan()

fun Activity.getQuantityHtmlSpannedString(@PluralsRes id: Int, quantity: Int): Spanned = resources.getQuantityString(id, quantity).toHtmlSpan()

fun Activity.getQuantityHtmlSpannedString(@PluralsRes id: Int, quantity: Int, vararg formatArgs: Any): Spanned = resources.getQuantityString(id, quantity, *formatArgs).toHtmlSpan()


fun Fragment.getHtmlSpannedString(@StringRes id: Int): Spanned = getString(id).toHtmlSpan()

fun Fragment.getHtmlSpannedString(@StringRes id: Int, vararg formatArgs: Any): Spanned = getString(id, *formatArgs).toHtmlSpan()

fun Fragment.getQuantityHtmlSpannedString(@PluralsRes id: Int, quantity: Int): Spanned = resources.getQuantityString(id, quantity).toHtmlSpan()

fun Fragment.getQuantityHtmlSpannedString(@PluralsRes id: Int, quantity: Int, vararg formatArgs: Any): Spanned = resources.getQuantityString(id, quantity, *formatArgs).toHtmlSpan()

@Himanshu Mori qualche frammento aiuterebbe. Lo stai usando nella classe Kotlin?
— svkaka,

1
Le estensioni delle attività non sono necessarie, Activity is Context stessa
— Farshad Tahmasbi

2

strings.xml

<string name="my_text"><Data><![CDATA[<b>Well Done !</b><br></br>All of your activities are completed.<br></br>You may now close the app.<br></br>See you again next time.]]></Data></string>

Impostare

textView.setText(Html.fromHtml(getString(R.string.activity_completed_text)));

1

Puoi farlo da stringa

 <resources xmlns:tools="http://schemas.android.com/tools">

 <string name="total_review"><b>Total Review: </b> </string>

 </resources>

e puoi accedervi dal codice java come

proDuctReviewNumber.setText(getResources().getString(R.string.total_review)+productDetailsSuccess.getProductTotalReview());

1

strings.xml

<string name="sentence">This price is <b>%1$s</b> USD</string>

page.java

String successMessage = getString(R.string.message,"5.21");

Questo prezzo è di 5,21 USD


1
È necessario utilizzare la funzionalità nativa per il passaggio dei parametri. Basta inserire "% 1 $ s" invece di "{1}" e chiamare getString (R.string.message, "5.21") senza sostituire ()
— Adrian Grygutis

I documenti supportano questa risposta: developer.android.com/guide/topics/resources/… Anche se deve essere passato attraverso un parser HTML
— ProjectDelta
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.