Che le bandiere non significano
Quando ho visto le INCLUSIVE
e EXCLUSIVE
parti delle Spannable
bandiere, ho pensato che hanno appena detto o meno la durata comprendeva le posizioni di inizio e di indice fine del brano. Questo non è vero. Lasciatemi illustrare ciò con il seguente esempio.
String myString = "";
int start = 1;
int end = 3;
int spanFlag = Spannable.SPAN_INCLUSIVE_INCLUSIVE; // this is what is changing
SpannableString spannableString = new SpannableString(myString);
ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(Color.RED);
spannableString.setSpan(foregroundSpan, start, end, spanFlag);
textView.setText(spannableString);
Ecco i risultati:
SPAN_INCLUSIVE_INCLUSIVE
SPAN_INCLUSIVE_EXCLUSIVE
SPAN_EXCLUSIVE_INCLUSIVE
SPAN_EXCLUSIVE_EXCLUSIVE
Sono tutti uguali! Le bandiere non influenzano lo span. Un'intervallo sempre include il carattere al suo indice iniziale ed esclude il carattere nell'indice finale.
Quali le bandiere significano veramente
I INCLUSIVE
e EXCLUSIVE
parti delle bandiere Spannable effettivamente dire se la campata dovrebbe includere testo che viene inserito all'inizio o alla fine posizioni.
Ecco un esempio modificato per illustrarlo.
String myString = "";
int start = 1;
int end = 3;
int spanFlag = Spannable.SPAN_INCLUSIVE_INCLUSIVE; // this is what is changing
// set the span
SpannableStringBuilder spannableString = new SpannableStringBuilder(myString);
ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(Color.RED);
spannableString.setSpan(foregroundSpan, start, end, spanFlag);
// insert the text after the span has already been set
// (inserting at start index second so that end index doesn't get messed up)
spannableString.insert(end, "x");
spannableString.insert(start, "x");
textView.setText(spannableString);
Ecco i risultati dopo l'inserimento di un x
alla fine e iniziare indici:
SPAN_INCLUSIVE_INCLUSIVE
SPAN_INCLUSIVE_EXCLUSIVE
SPAN_EXCLUSIVE_INCLUSIVE
SPAN_EXCLUSIVE_EXCLUSIVE
Note
- La maggior parte di questa risposta descrive cose del PO già conosceva. Lo sto solo aggiungendo per i futuri visitatori come me che non conoscevano queste cose.
- Nel secondo esempio ho dovuto usare un
SpannableStringBuilder
perché il testo in un SpannableString
è immutabile, quindi non è possibile inserire del testo in esso. Pertanto, le bandiere sono generalmente prive di significato per un SpannableString
.Tuttavia, si potrebbe immaginare una situazione in cui gli span da uno SpannableString
vengono copiati su un SpannableStringBuilder
o Editable
, e da lì le bandiere avrebbero un significato.
- See this answer per la differenza tra
SpannableString
, SpannableStringBuilder
, Editable
e altro.
, buona risposta. Puoi spiegare altre bandiere con spanning? Si prega di consultare http://stackoverflow.com/q/16392417/596555 – boiledwater