2

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?

Nicky
  • 31
  • 1
  • 5

3 Answers3

0

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?

Community
  • 1
  • 1
jbihan
  • 3,053
  • 2
  • 24
  • 34
  • I have been in that thread and it is helpful. But the problem is I don't know the index at which to start the formating as every tweet will be different. I'll need a way to check for when "@" starts, store that index and store the index of the next space. Same goes with http and # – Nicky Sep 02 '13 at 00:36
  • Well, you have several methods in Java to get the position of a substring : http://stackoverflow.com/questions/2615749/java-method-to-get-position-of-a-match-in-a-string – jbihan Sep 02 '13 at 00:49
  • This is a flat out terrible idea. Using the Html class is *so much* slower than using a Spannable (which is what the Html class itself gets the text down to) directly, as the answer from manutudescends recommends. Look at the Html class's source code yourself to see: https://github.com/android/platform_frameworks_base/blob/master/core/java/android/text/Html.java#L422 – Kasra Rahjerdi Sep 02 '13 at 02:07
0

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;
        }
    }
Nicky
  • 31
  • 1
  • 5