问题
Is there a way to add a tab character to a piece of text using span
in textview
? From the developer documentation, I came across TabStopSpan
(see here) and tried to use it in a TextView
like so:
String source = "Hello World! Let's select some text!!";
SpannableString s = new SpannableString(source);
s.setSpan(new TabStopSpan() {
@Override
public int getTabStop() {
return 100;
}
}, 5, 10, 0);
ed.setText(s, BufferType.SPANNABLE);
Where ed is a TextView
. The above snippet does not do anything and the documentation is so less as to be pretty much useless. Is there any way to add a tab character to a TextView
using spans?
回答1:
Just add "\t" for a tab, "\n" for a new line. For example:
String source = "Hello!\tLets select some text!";
回答2:
Yes. combination of "\t" and TabStopSpannable will do the trick. The snippet below adds a tab between firstString and secondString:
SpannableStringBuilder span = new SpannableStringBuilder(firstString +"\t"+ secondString);
span.setSpan(new TabStopSpan.Standard(600), 0, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE );
}
((TextView) v).setText(span, TextView.BufferType.SPANNABLE);
Be careful to use a meaningful value in the TabStopSpan.Standard constructor, preferably based on screendimensions.
回答3:
use this.
public static SpannableStringBuilder getTabText(String text, float stop)
{
int column = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, stop, SystemMaster.getResources().getDisplayMetrics());
SpannableStringBuilder span = new SpannableStringBuilder(text);
span.setSpan(new TabStopSpan.Standard(column), 0, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return span;
}
and then
Text text = "xx \t yy \n aa \t bb";
SpannableStringBuilder sp = TextHelper.getTabText(text, 100);
tv.setText(sp);
来源:https://stackoverflow.com/questions/19121125/using-span-to-insert-tab-in-textview