Czy można mieć wiele stylów wewnątrz widoku tekstowego?
Czy Można ustawić wiele stylów dla różnych fragmentów tekstu wewnątrz widoku tekstowego?
Na przykład ustawiam tekst w następujący sposób:
tv.setText(line1 + "\n" + line2 + "\n" + word1 + "\t" + word2 + "\t" + word3);
Czy można mieć inny styl dla każdego elementu tekstu? Np. line1 bold, word1 italic itp.
[2]} Typowe zadania dla programistów i jak je wykonywać w Androidzie obejmują Zaznaczanie, podświetlanie lub stylizowanie fragmentów tekstu :// Get our EditText object. EditText vw = (EditText)findViewById(R.id.text); // Set the EditText's text. vw.setText("Italic, highlighted, bold."); // If this were just a TextView, we could do: // vw.setText("Italic, highlighted, bold.", TextView.BufferType.SPANNABLE); // to force it to use Spannable storage so styles can be attached. // Or we could specify that in the XML. // Get the EditText's internal text storage Spannable str = vw.getText(); // Create our span sections, and assign a format to each. str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); str.setSpan(new BackgroundColorSpan(0xFFFFFF00), 8, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 21, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Ale to używa wyraźnej pozycji liczby w tekście. Jest na to jakiś czystszy sposób?
17 answers
W razie gdyby ktoś zastanawiał się jak to zrobić, oto jeden sposób: (jeszcze raz dzięki Markowi!)
mBox = new TextView(context);
mBox.setText(Html.fromHtml("<b>" + title + "</b>" + "<br />" +
"<small>" + description + "</small>" + "<br />" +
"<small>" + DateAdded + "</small>"));
Aby uzyskać nieoficjalną listę tagów obsługiwanych przez tę metodę, Zobacz ten link lub to pytanie: które tagi HTML są obsługiwane przez Android TextView?
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:47:30
Spróbuj Html.fromHtml()
i oznacz swój tekst pogrubionymi i kursywnymi znacznikami HTML, np.:
Spanned text = Html.fromHtml("This mixes <b>bold</b> and <i>italic</i> stuff");
textView.setText(text);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-31 21:30:15
Nieco off-topic, ale uznałem to za zbyt przydatne, aby o tym tutaj nie wspominać.
Co jeśli chcielibyśmy przeczytać tekst Html z string.zasoby xml, a tym samym ułatwiają lokalizację. CDATA make this possible:
<string name="my_text">
<![CDATA[
<b>Autor:</b> Mr Nice Guy<br/>
<b>Contact:</b> [email protected]<br/>
<i>Copyright © 2011-2012 Intergalactic Spacebar Confederation </i>
]]>
</string>
Z naszego kodu Javy możemy teraz używać go w następujący sposób:
TextView tv = (TextView) findViewById(R.id.myTextView);
tv.setText(Html.fromHtml(getString(R.string.my_text)));
Nie spodziewałem się, że to zadziała. Ale tak się stało.
Mam nadzieję, że jest to przydatne dla niektórych z was!
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-03 11:20:44
Jeśli nie masz ochoty używać html, możesz po prostu utworzyć style.xml i użyj go w ten sposób:
TextView tv = (TextView) findViewById(R.id.textview);
SpannableString text = new SpannableString(myString);
text.setSpan(new TextAppearanceSpan(getContext(), R.style.myStyle), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setSpan(new TextAppearanceSpan(getContext(), R.style.myNextStyle), 6, 10, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(text, TextView.BufferType.SPANNABLE);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-29 12:46:49
Lista obsługiwanych tagów to:
Jeśli używasz zasobu tekstowego, możesz dodać kilka prostych stylów, takich jak pogrubienie lub kursywa, używając notacji HTML. Aktualnie obsługiwane znaczniki to:
B
(pogrubienie),I
(kursywa),U
(podkreślenie),TT
(monospace),BIG
,SMALL
,SUP
(indeks górny),SUB
(indeks dolny) iSTRIKE
(Przekreślenie). Tak więc, na przykład, wres/values/strings.xml
możesz zadeklarować to:<resource> <string id="@+id/styled_welcome_message">We are <b><i>so</i></b> glad to see you.</string> </resources>
(od http://developer.android.com/guide/faq/commontasks.html#selectingtext - Web Archive link, <resource>
literówka jest w oryginale!)
Pokazuje również, że {[12] }nie jest tak naprawdę potrzebny w prostych przypadkach.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-08 18:29:19
Jest bardziej lekki używać SpannableString
zamiast znaczników html. Pomaga mi to zobaczyć wizualne przykłady, więc oto odpowiedź uzupełniająca.
To jest pojedynczy TextView
.
// set the text
SpannableString s1 = new SpannableString("bold\n");
SpannableString s2 = new SpannableString("italic\n");
SpannableString s3 = new SpannableString("foreground color\n");
SpannableString s4 = new SpannableString("background color\n");
SpannableString s5 = new SpannableString("underline\n");
SpannableString s6 = new SpannableString("strikethrough\n");
SpannableString s7 = new SpannableString("bigger\n");
SpannableString s8 = new SpannableString("smaller\n");
SpannableString s9 = new SpannableString("font\n");
SpannableString s10 = new SpannableString("URL span\n");
SpannableString s11 = new SpannableString("clickable span\n");
SpannableString s12 = new SpannableString("overlapping spans\n");
// set the style
int flag = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE;
s1.setSpan(new StyleSpan(Typeface.BOLD), 0, s1.length(), flag);
s2.setSpan(new StyleSpan(Typeface.ITALIC), 0, s2.length(), flag);
s3.setSpan(new ForegroundColorSpan(Color.RED), 0, s3.length(), flag);
s4.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, s4.length(), flag);
s5.setSpan(new UnderlineSpan(), 0, s5.length(), flag);
s6.setSpan(new StrikethroughSpan(), 0, s6.length(), flag);
s7.setSpan(new RelativeSizeSpan(2), 0, s7.length(), flag);
s8.setSpan(new RelativeSizeSpan(0.5f), 0, s8.length(), flag);
s9.setSpan(new TypefaceSpan("monospace"), 0, s9.length(), flag);
s10.setSpan(new URLSpan("https://developer.android.com"), 0, s10.length(), flag);
s11.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
Toast.makeText(getApplicationContext(), "Span clicked", Toast.LENGTH_SHORT).show();
}
}, 0, s11.length(), flag);
s12.setSpan(new ForegroundColorSpan(Color.RED), 0, 11, flag);
s12.setSpan(new BackgroundColorSpan(Color.YELLOW), 4, s12.length(), flag);
s12.setSpan(new UnderlineSpan(), 4, 11, flag);
// build the string
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append(s1);
builder.append(s2);
builder.append(s3);
builder.append(s4);
builder.append(s5);
builder.append(s6);
builder.append(s7);
builder.append(s8);
builder.append(s9);
builder.append(s10);
builder.append(s11);
builder.append(s12);
// set the text view with the styled text
textView.setText(builder);
// enables clicking on spans for clickable span and url span
textView.setMovementMethod(LinkMovementMethod.getInstance());
Dalsze Badania
- wyjaśnij znaczenie znaczników Span, takich jak SPAN_EXCLUSIVE_EXCLUSIVE
- Android Spanned, SpannedString, Spannable, SpannableString i CharSequence
- rodzaje przęseł
Ten przykład pochodzi z tutaj .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:18:30
Miałem ten sam problem. Mógłbym użyć fromHtml, ale jestem teraz Androidem, a nie Internetem, więc postanowiłem to wypróbować. Muszę to jednak zlokalizować, więc dałem mu szansę za pomocą koncepcji wymiany strun. Ustawiłem styl w widoku tekstu jako główny styl, a następnie sformatowałem inne peices.
Mam nadzieję, że pomoże to innym, którzy chcą zrobić to samo - Nie wiem, dlaczego nie jest to łatwiejsze w ramach.
Moje struny wyglądają tak:
<string name="my_text">{0} You will need a {1} to complete this assembly</string>
<string name="text_sub0">1:</string>
<string name="text_sub1">screwdriver, hammer, and measuring tape</string>
Oto style:
<style name="MainStyle">
<item name="android:textSize">@dimen/regular_text</item>
<item name="android:textColor">@color/regular_text</item>
</style>
<style name="style0">
<item name="android:textSize">@dimen/paragraph_bullet</item>
<item name="android:textColor">@color/standout_text</item>
<item name="android:textStyle">bold</item>
</style>
<style name="style1">
<item name="android:textColor">@color/standout_light_text</item>
<item name="android:textStyle">italic</item>
</style>
Oto Mój kod, który wywołuje metodę formatStyles:
SpannableString formattedSpan = formatStyles(getString(R.string.my_text), getString(R.string.text_sub0), R.style.style0, getString(R.string.main_text_sub1), R.style.style1);
textView.setText(formattedSpan, TextView.BufferType.SPANNABLE);
Metoda formatu:
private SpannableString formatStyles(String value, String sub0, int style0, String sub1, int style1)
{
String tag0 = "{0}";
int startLocation0 = value.indexOf(tag0);
value = value.replace(tag0, sub0);
String tag1 = "{1}";
int startLocation1 = value.indexOf(tag1);
if (sub1 != null && !sub1.equals(""))
{
value = value.replace(tag1, sub1);
}
SpannableString styledText = new SpannableString(value);
styledText.setSpan(new TextAppearanceSpan(getActivity(), style0), startLocation0, startLocation0 + sub0.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
if (sub1 != null && !sub1.equals(""))
{
styledText.setSpan(new TextAppearanceSpan(getActivity(), style1), startLocation1, startLocation1 + sub1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return styledText;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-07 23:22:09
Teraz element <b>
jest przestarzały. <strong>
renderuje jako <b>
i <em>
renderuje jako <i>
.
tv.setText(Html.fromHtml("<strong>bold</strong> and <em>italic</em> "));
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-05 16:30:46
Jeśli chcesz mieć możliwość dodania stylizowanego tekstu w xml, możesz utworzyć niestandardowy widok rozszerzający Widok TextView i nadpisać setText ():
public class HTMLStyledTextView extends TextView
{
public HTMLStyledTextView(Context context) {
super(context);
}
public HTMLStyledTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public HTMLStyledTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void setText(CharSequence text, BufferType type)
{
super.setText(Html.fromHtml(text.toString()), type);
}
}
Następnie możesz go użyć w następujący sposób (zastąp {[2] } nazwą pakietu):
<PACKAGE_NAME.HTMLStyledTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="<![CDATA[
<b>Bolded Text:</b> Non-Bolded Text
]]>"
/>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-20 00:07:03
Oto prosty sposób, aby to zrobić za pomocą HTMLBuilder
myTextView.setText(new HtmlBuilder().
open(HtmlBuilder.Type.BOLD).
append("Some bold text ").
close(HtmlBuilder.Type.BOLD).
open(HtmlBuilder.Type.ITALIC).
append("Some italic text").
close(HtmlBuilder.Type.ITALIC).
build()
);
Wynik:
Trochę pogrubionego tekstu Some italic text
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-03 07:27:14
Jak podano, użyj TextView.setText(Html.fromHtml(String))
I użyj tych znaczników w łańcuchu HTML sformatowanym:
<a href="...">
<b>
<big>
<blockquote>
<br>
<cite>
<dfn>
<div align="...">
<em>
<font size="..." color="..." face="...">
<h1>
<h2>
<h3>
<h4>
<h5>
<h6>
<i>
<img src="...">
<p>
<small>
<strike>
<strong>
<sub>
<sup>
<tt>
<u>
Http://commonsware.com/blog/Android/2010/05/26/html-tags-supported-by-textview.html
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-03 11:45:51
Ja Też
Może użyjesz jakiegoś pięknego znacznika z Kotlinem i Anko -
import org.jetbrains.anko.*
override fun onCreate(savedInstanceState: Bundle?) {
title = "Created with Beautiful Markup"
super.onCreate(savedInstanceState)
verticalLayout {
editText {
hint = buildSpanned {
append("Italic, ", Italic)
append("highlighted", backgroundColor(0xFFFFFF00.toInt()))
append(", Bold", Bold)
}
}
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-14 08:00:58
W rzeczywistości, oprócz obiektu Html, można również użyć klas typu Spannable, np. TextAppearanceSpan lub TypefaceSpan i SpannableString togather. Klasa Html również wykorzystuje te mechanizmy. Ale z klasami typowymi, masz więcej swobody.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-11 10:01:21
Może to być tak proste, jak wykorzystanie metody length () łańcucha:
Podziel ciąg tekstowy w pliku XML Strings na tyle podciągów (oddzielny ciąg z punktu widzenia Androida), ile potrzebujesz różnych stylów, więc może to być: str1, str2, str3 (jak w Twoim przypadku), które po połączeniu są całym pojedynczym ciągiem, którego używasz.
A następnie po prostu postępuj zgodnie z metodą "Span", tak jak przedstawiłeś swój kod - ale zamiast pojedynczego ciągu, połącz wszystkie podciągi łącząc je w jeden, każdy z innym niestandardowym stylem.
Nadal używasz liczb, jednak nie bezpośrednio - nie mają już twardej formy (jak w Twoim kodzie), ale są zastępowane metodami combined length () (zwróć uwagę na dwie gwiazdki poprzedzające i przyrostek str.length() w miejsce liczby bezwzględnej do usunięcia zmiany):
str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, **str.length()**, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Dla pierwszego rozmiaru łańcucha, następnie str.długość () + 1, str.długość () + str2.length () dla drugiego rozmiaru łańcucha i tak dalej ze wszystkimi podłańcuchami, zamiast np. 0,7 lub 8,19 i tak dalej...
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-11 09:30:58
Używanie pomocniczej klasy Spannable jako Android String Resources u dołu strony. Możesz do tego podejść, tworząc CharSquences
i nadając im styl.
Ale w przykładzie, który nam podają, jest tylko dla pogrubienia, kursywy, a nawet kolorowania tekstu. Musiałem zawinąć kilka stylów w CharSequence
, aby ustawić je w TextView
. Więc do tej klasy (nazwałem ją CharSequenceStyles
) dodałem właśnie tę funkcję.
public static CharSequence applyGroup(LinkedList<CharSequence> content){
SpannableStringBuilder text = new SpannableStringBuilder();
for (CharSequence item : content) {
text.append(item);
}
return text;
}
I w widoku dodałem to.
message.push(postMessageText);
message.push(limitDebtAmount);
message.push(pretMessageText);
TextView.setText(CharSequenceStyles.applyGroup(message));
Mam nadzieję, że to pomoże ty!
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-07 23:15:18
Spanny sprawiają, że spannablestring jest łatwiejszy w użyciu.
Spanny spanny = new Spanny("Underline text", new UnderlineSpan())
.append("\nRed text", new ForegroundColorSpan(Color.RED))
.append("\nPlain text");
textView.setText(spanny)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-17 15:53:22
Jak powiedział Jon , dla mnie jest to najlepsze rozwiązanie i nie musisz ustawiać żadnego tekstu w czasie wykonywania, użyj tylko tej niestandardowej klasy HtmlTextView
public class HtmlTextView extends TextView {
public HtmlTextView(Context context) {
super(context);
}
public HtmlTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public HtmlTextView(Context context, AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
}
@TargetApi(21)
public HtmlTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public void setText(CharSequence s,BufferType b){
super.setText(Html.fromHtml(s.toString()),b);
}
}
I to wszystko, teraz tylko umieścić go w XML
<com.fitc.views.HtmlTextView
android:id="@+id/html_TV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/example_html" />
Z Twoim łańcuchem Html
<string name="example_html">
<![CDATA[
<b>Author:</b> Mr Donuthead<br/>
<b>Contact:</b> [email protected]<br/>
<i>Donuts for life </i>
]]>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-18 12:46:25