开发者

Is it possible to change text color for one database item when it is printed from a cursor?

开发者 https://www.devze.com 2023-03-10 13:35 出处:网络
I have a database that I use a cursor to display. What I am doing right now is just appending the results to a string and displaying. What I am trying to do is change the text color of the title of ea

I have a database that I use a cursor to display. What I am doing right now is just appending the results to a string and displaying. What I am trying to do is change the text color of the title of each database result based on the type of item it is but I don't think that is possible when appending text using a Stringbuilder.

Is there something else I could use to make this possible or have I overlooked something using Stringbuilder that would allow me to do this?

Here is an example o开发者_运维百科f the output I am trying to get:

Item Name 1 (blue) Item Description (white) Rating (white) Model (white)

Item Name 2 (red) Item Description (white) Rating (white) Model (white)

Item Name 3 (green) Item Description (white) Rating (white) Model (white)

Item Name 4 (green) Item Description (white) Rating (white) Model (white)

And so on...

The color of the Item Name field would depend on the item itself. Thanks for any help or point in the right direction.

Edit 1 Here is a shortened example (with some of the database columns taken out) of how I am displaying the results:

public void showItems(Cursor cursor) {
    StringBuilder ret = new StringBuilder();
    while (cursor.moveToNext()) {
        String name = cursor.getString(1);
        String model = cursor.getString(2);
        ret.append(name + "\n" + model + "\n);
    }
    sResults.setText(ret);
}

It's from a tutorial I found online and works great except for the whole changing certain parts of the text to a different color.

Edit 2 Based on the below suggestion I have tried this:

public void showItems(Cursor cursor) {
    StringBuilder ret = new StringBuilder();
    while (cursor.moveToNext()) {
        String name = cursor.getString(1);
        String model = cursor.getString(2);
        Spanned styleText = (Html.fromHtml("<b><style='color:red;'>" + name + "</style></b><br />" + model + "<br />"));

        ret.append(styleText);
    }
    sResults.setText(ret);
}

I get the same results as my original code without any color. Any other suggestions?


Use fromHtml: this will allow you to style your string.

   String styleText = "This is <style='color:red;'>red</style>.";
   textView.setText(Html.fromHtml(styleText), TextView.BufferType.SPANNABLE);
0

精彩评论

暂无评论...
验证码 换一张
取 消