在 android 列表视图中设置文本颜色和大小

Setting text color and size in android listview

我正在尝试为 Android 中的 ListView 中的字符串设置文本大小和颜色。使用 spannable strings 来达到这个目标。这是我的代码(来自 onCreate):

statusInfo = new String[jArray.length()];

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, statusInfo);
        formList.setAdapter(adapter);

SpannableStringBuilder secondPart = new SpannableStringBuilder("Status: " + formStatus + " - Window: " + formWindowStart + " - " + formWindowEnd);

            int cs_blue = getResources().getColor(R.color.cs_blue);
            int green = getResources().getColor(R.color.green);


            if(fs == -1)
            {
                ForegroundColorSpan fcs = new ForegroundColorSpan(cs_blue);
                secondPart.setSpan(fcs, 0, secondPart.length(), 0);
            }
            if(fs == 1)
            {
                ForegroundColorSpan fcs = new ForegroundColorSpan(green);
                secondPart.setSpan(fcs, 0, secondPart.length(), 0);
            }


            //need text size of 12...85.714% of 14
            secondPart.setSpan(new RelativeSizeSpan(0.85714f), 0, secondPart.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

问题是文本仍然是黑色且大小正常。不知道为什么它不改变大小和颜色。我查看了其他几个问题,但仍然无法正常工作。

如有任何帮助,我们将不胜感激。谢谢!

好的,我想我遇到了你的问题。

你可以看看TextView的Sourcecode

您需要的是:

  1. 您的文本被识别为 Spannable,因此可以应用不同的样式

  2. 您的视图必须更新

两者都发生在 setText。 所以如果你要改变样式,我认为最简单的方法是使用setText。

在 xml 中只需设置

android:textColor="#ff0000"
android:textSize="10dp" // 10sp

举个例子