568

TextView内の異なるテキストに複数のスタイルを設定することは可能ですか?

たとえば、テキストを次のように設定しています。

tv.setText(line1 + "\n" + line2 + "\n" + word1 + "\t" + word2 + "\t" + word3);

テキスト要素ごとに異なるスタイルを設定することはできますか?たとえば、line1は太字、word1は斜体などです。

開発者ガイドの一般的なタスクとAndroidでそれらを実行する方法には、テキストの一部の選択、強調表示、またはスタイリングが含まれます。

// 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);

ただし、テキスト内で明示的な位置番号を使用します。これを行うためのよりクリーンな方法はありますか?

4

20 に答える 20

703

誰かがこれを行う方法を疑問に思っている場合に備えて、ここに 1 つの方法があります: (Mark に再び感謝します!)

mBox = new TextView(context);
mBox.setText(Html.fromHtml("<b>" + title + "</b>" +  "<br />" + 
            "<small>" + description + "</small>" + "<br />" + 
            "<small>" + DateAdded + "</small>"));

このメソッドでサポートされているタグの非公式リストについては、このリンクまたはこの質問を参照してください: Android TextView でサポートされている HTML タグは?

于 2009-10-07T18:58:11.570 に答える
220

を試してHtml.fromHtml()、太字と斜体の HTML タグでテキストをマークアップしてください。

Spanned text = Html.fromHtml("This mixes <b>bold</b> and <i>italic</i> stuff");
textView.setText(text);
于 2009-10-07T13:03:54.780 に答える
192

Slightly off-topic, but I found this too useful not to be mentioned here.

What if we would like to read the the Html text from string.xml resource and thus make it easy to localize. CDATA make this possible:

<string name="my_text">
  <![CDATA[
    <b>Autor:</b> Mr Nice Guy<br/>
    <b>Contact:</b> myemail@grail.com<br/>
    <i>Copyright © 2011-2012 Intergalactic Spacebar Confederation </i>
  ]]>
</string> 

From our Java code we could now utilize it like this:

TextView tv = (TextView) findViewById(R.id.myTextView);
tv.setText(Html.fromHtml(getString(R.string.my_text))); 

I did not expect this to work. But it did.

Hope it's useful to some of you!

于 2011-11-03T11:20:44.270 に答える
140

HTML を使いたくない場合は、styles.xml を作成して次のように使用できます。

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);
于 2012-03-14T20:40:21.880 に答える
46

サポートされているタグのリストは次のとおりです。

文字列リソースを使用する場合は、HTML 表記を使用して太字や斜体などの簡単なスタイルを追加できます。現在サポートされているタグはB、(太字)、I(斜体)、U(下線)、TT(モノスペース)、、、BIG(上付き文字)、SMALL(下付き文字) 、および(取り消し線) です。したがって、たとえば、次のように宣言できます。SUPSUBSTRIKEres/values/strings.xml

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

( http://developer.android.com/guide/faq/commontasks.html#selectingtext — Web アーカイブ リンクから、<resource>タイプミスはオリジナルです!)

Html.fromHtmlまた、単純なケースでは実際には必要ないことも示しています。

于 2010-09-02T08:57:57.350 に答える
17

私は同じ問題に遭遇していました。fromHtml を使用することもできましたが、現在は web ではなく android であるため、これを試してみることにしました。ただし、これをローカライズする必要があるため、文字列置換の概念を使用して試してみました。TextView のスタイルをメイン スタイルに設定してから、他のピースをフォーマットします。

これが同じことをしようとしている他の人に役立つことを願っています-フレームワークでこれが簡単ではない理由がわかりません.

私の文字列は次のようになります。


<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>

スタイルは次のとおりです。


<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>

私の 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);

フォーマット方法:


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;
}
于 2013-01-07T23:22:09.420 に答える
8

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()
    );

結果:

一部の太字のテキスト 一部の斜体のテキスト

于 2015-09-03T07:27:14.330 に答える
7

スタイル付きテキストを xml に追加できるようにしたい場合は、TextView を拡張して 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);
    }
}

次に、次のように使用できます (PACKAGE_NAMEパッケージ名に置き換えます)。

<PACKAGE_NAME.HTMLStyledTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="<![CDATA[
        <b>Bolded Text:</b> Non-Bolded Text
    ]]>"
/>
于 2014-08-20T00:07:03.693 に答える
7

述べたように、使用TextView.setText(Html.fromHtml(String))

そして、Html 形式の文字列でこれらのタグを使用します。

<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

于 2015-10-03T11:45:51.133 に答える
3

私もです

Kotlin と 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)
            }
        }
    }
}

美しいマークアップで作成

于 2017-11-14T08:00:58.980 に答える
0

String の length() メソッドを利用するのと同じくらい簡単かもしれません。

  1. Strings XML ファイルのテキスト文字列を、さまざまなスタイルが必要な数の部分文字列 (Android の観点からは別の文字列) に分割します。結合すると、使用する単一の文字列全体になります。

  2. 次に、コードで提示したのと同じように、単に「スパン」メソッドに従いますが、単一の文字列の代わりに、すべての部分文字列を結合して単一の文字列に結合し、それぞれ異なるカスタム スタイルを使用します。

数字は引き続き使用しますが、直接ではありません。(コードのように) ハードコーディングされた形式ではなくなりましたが、結合された length() メソッドに置き換えられています (str の前と末尾にある 2 つの星に注意してください。 length() を絶対数の代わりに使用して、変更を無効にします):

str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, **str.length()**, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

最初の文字列サイズの場合はstr.length() + 1、2番目の文字列サイズの場合は str.length() + str2.length() というように、0,7 や 8,19 などの代わりに、すべての部分文字列について同様です。等々...

于 2016-08-11T09:30:58.460 に答える
0

ジョンが言ったように、私にとってこれは最良の解決策であり、実行時にテキストを設定する必要はありません。このカスタム クラス 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);
  }

}

それだけです。今は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" />

あなたのHtml文字列で

<string name="example_html">
<![CDATA[
<b>Author:</b> Mr Donuthead<br/>
<b>Contact:</b> me@donut.com<br/>
<i>Donuts for life </i>
]]>

于 2017-10-18T12:46:25.533 に答える