resource programacion crear como array android arrays string formatting bold

programacion - string array android



Formato de texto de matriz de cadenas (3)

Tengo esta cadena:

String[] text = {"Address 1: Street nr.45 ", "Address 2: Street nr.67", "Address 3: Street nr. 56 /n Phone number: 000000000"};

Que se usa más tarde por:

((TextView)findViewById(R.id.adresa)).setText(text[newSelectedAddress]);

al seleccionar un artículo de un girador.

¿Cómo puedo agregar formato al texto dentro de la cadena? Quiero que la dirección esté en negrita, Street nr. con cursiva


Tienes que usar Spannable s. Aunque crearlos es un poco prolijo y parece complejo, no es ciencia espacial. Un ejemplo:

String source = "This is example text"; SpannedString out = new SpannedString(source); StyleSpan boldSpan = new StyleSpan(Typeface.BOLD); StyleSpan boldSpan2 = new StyleSpan(Typeface.BOLD); out.setSpan(boldSpan, 1, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); out.setSpan(boldSpan2, 9, 12, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

Resultado: T hi s es e xam ple texto

A continuación, estableceTexto esta Spannable en lugar de la cadena normal.


Haz como este mi querido amigo:

String[] text = {"Address 1: Street nr.45 ", "Address 2: Street nr.67", "Address 3: Street nr. 56 /n Phone number: 000000000"}; String tempString = text[newSelectedAddress]; CharSequence charSeq= new SpannedString(tempString); Spannable spannable = (Spannable) charSeq; StyleSpan boldSpan = new StyleSpan(Typeface.BOLD); StyleSpan boldSpan2 = new StyleSpan(Typeface.ITALIC); spannable.setSpan(boldSpan, 0, "Address".length()-1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); spannable.setSpan(boldSpan2, tempString.indexOf("Street"), tempString.indexOf("Street")-1 +"Street".length()-1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); ((TextView)findViewById(R.id.adresa)).setText(spannable);

Gracias


Hay un poco de truco para permitir que las cadenas reconozcan html para el formato en negrita y cursiva. Agrega algo como esto a tus strings.xml:

<string name="address"><![CDATA[<b>Address %1$s</b>: <i>Street nr. %2$s </i>]]></string>

Entonces:

Resources res = getResources(); formattedString = res.getString(R.string.address, "1", "45"); // equivalent to String.format(res.getString(R.string.address), "1", "45") Spannable s = Html.from Html(formattedString); textView.setText(s);