Nicky
Nicky

Reputation: 31

How to format TextView text in Android?

I'm creating an Twitter application and I've been struggling to find an efficient way to format tweets.

Example tweet: "RT @BlahBlah this is a tweet http://link.com #Hello"

I want to format certain parts of this string. Eg, hyperlinks are blue, hashtags grey and @xxxs are green

How would I do this?

Upvotes: 2

Views: 8238

Answers (3)

Nicky
Nicky

Reputation: 31

This works but I don't think it's efficient as it will have to iterate through the whole string. An i'll need to do it for alot of tweets... Is there a better and more efficient way?

    int atStart = 0;
    int atEnd = 0;
    boolean atFound = false;

    String regex = "\\W";

    System.out.println(str.length());

    for(int i = 0;i < str.length();i++)
    {
        String a = Character.toString(str.charAt(i));

        if(a.matches(regex)| i==str.length()-1 && atFound)
        {
            System.out.println(i + "REGEX MATCH");

            if(i== str.length()-1)
            {
                atEnd = i+1;
            }else
            atEnd = i;

            i--; // <- decrement. otherwise "@hello@hello" won't change

            atFound = false;

            str.setSpan(new BackgroundColorSpan(0xFFFF0000), atStart,
                    atEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }else

        if(a.equals("@"))
        {
            atStart = i;
            atFound = true;
        }
    }

Upvotes: 0

jbihan
jbihan

Reputation: 3099

In fact you can format the text inside the TextView using HTML tags. I have a look at excellent this thread, I gues it should answer your question : Is it possible to have multiple styles inside a TextView?

Upvotes: 0

Related Questions