动态地在一个textview中设置两种不同的颜色

时间:2013-10-11 12:19:43

标签: android

Hello Friends我在单个textview中设置了两种不同的颜色,如下所示 Output Screen

我的代码如下

public static String getAnswers(List<Question> questions) {
    int question = 1;
    StringBuffer sb = new StringBuffer();
    for (Question q : questions){
        String d= "<font color=#292929>" +   sb.append("Q").append(question).append(") ").append(q.getQuestion()).append("? \n")+"</font>";
        String ss="<font color=#ce4e00>"+sb.append("Answer: ").append(q.getAnswer()).append("\n\n")+"</font>";

            AnswersActivity.results.setText(Html.fromHtml(d+ss),TextView.BufferType.SPANNABLE);
        question ++;
    }

    return sb.toString();
}

并且是我设置的textview

        mStringQustion = Utility.getAnswers(currentGame.getQuestions());

并获得如下所示的输出

Output iMAge

我该如何解决?

2 个答案:

答案 0 :(得分:2)

我遇到了同样的问题,我修好了如下

您应该使用 ForegroundColorSpan

String firstString = "Book Title:";
String secondString = "Book Description";
String thirdString = "1.SubTitle";

        SpannableStringBuilder stringBuilder = new SpannableStringBuilder(
                firstString + "\n" + secondString + "\n" + thirdString);
        stringBuilder.setSpan(new RelativeSizeSpan(2.0f), 0,
                firstString.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        stringBuilder.setSpan(new StyleSpan(
                android.graphics.Typeface.BOLD_ITALIC), firstString.length(),
                firstString.length() + secondString.length() + 1,
                Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        stringBuilder.setSpan(
                new ForegroundColorSpan(Color.rgb(255, 0, 0)),
                firstString.length() + secondString.length() + 1,
                firstString.length() + secondString.length()
                        + thirdString.length() + 2,
                Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        AnswersActivity.results.setText.setText(stringBuilder);

enter image description here

您可以根据自己的文字进行更改。

希望这会对你有所帮助。

答案 1 :(得分:0)

试试这个

String d = "&lt;![CDATA[ &lt;font color=#292929>" + sb.append("Q").append(question).append(")").append(q.getQuestion()).append("? \n")+"</font>";  
String ss="<font color=#ce4e00>" + sb.append("Answer:").append(q.getAnswer()).append("\n\n")+"</font>]]>";