首页 文章

android - 一个textview中的不同颜色

提问于
浏览
0

我想知道如何根据textview重复在单个textview中定义不同的颜色,例如:

如果我声明如下:Color [] colors = {Color.green,Color.blue,Color.red,Color.brown,Color.yellow};

然后我想在tv.setBackgroundColor(Color.GREEN)中以某种方式传递“颜色”;而不是“Color.green”,以便如果textview重复五次,我可以看到绿色,蓝色,红色,棕色和黄色的textview,如果它是7次,我可以得到绿色,蓝色,红色,棕色,黄色,绿色和蓝色 .

这是一些代码,加上一个图像

adapter = new SimpleCursorAdapter(this, R.layout.hrprocess_item_list, cursor, from, to, 0);
    adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
            if (view.getId() == R.id.category) {
              String s=cursor.getString(cursor.getColumnIndex(manager.CONTENT_CATEGORY));
                TextView tv = (TextView)view;               
               int[] androidColors = getResources().getIntArray(R.array.androidcolors);
               for (int i = 0; i < androidColors.length; i++) {
                   tv.setBackgroundColor(androidColors[i]);
                }
              tv.setText(s);
                return true;
            }
            return false;
        }

    });
    lv.setAdapter(adapter);

Colors.xml

<item name="azul1" type="color">#4178BE</item>
<item name="verde1" type="color">#008571</item>
<item name="morado1" type="color">#9855D4</item>
<item name="rojo1" type="color">#E71D32</item>
<item name="rojo_naranja1" type="color">#D74108</item>
<item name="amarillo1" type="color">#EFC100</item>
<item name="gris1" type="color">#6D7777</item>


<integer-array name="androidcolors">
    <item>@color/azul1</item>
    <item>@color/verde1</item>
    <item>@color/morado1</item>
    <item>@color/rojo1</item>
    <item>@color/rojo_naranja1</item>
    <item>@color/amarillo1</item>
    <item>@color/gris1</item>

</integer-array>

http://i.stack.imgur.com/dCQep.jpg

1 回答

  • 2

    您需要将 BackgroundColorSpan 个对象应用于您感兴趣的范围,而不是使用 setBackgroundColor() .

    This sample project应用 BackgroundColorSpan 突出显示 TextView 中的搜索结果:

    private void searchFor(String text) {
        TextView prose=(TextView)findViewById(R.id.prose);
        Spannable raw=new SpannableString(prose.getText());
        BackgroundColorSpan[] spans=raw.getSpans(0,
                                                 raw.length(),
                                                 BackgroundColorSpan.class);
    
        for (BackgroundColorSpan span : spans) {
          raw.removeSpan(span);
        }
    
        int index=TextUtils.indexOf(raw, text);
    
        while (index >= 0) {
          raw.setSpan(new BackgroundColorSpan(0xFF8B008B), index, index
              + text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
          index=TextUtils.indexOf(raw, text, index + text.length());
        }
    
        prose.setText(raw);
      }
    

    在您的情况下,您将旋转颜色,而不是使用我正在使用的颜色的硬编码十六进制值 .

相关问题