Question

What im trying to accomplish is something that is standard in most twitter apps, in a textview there may be an "@" mention or a "#" hashtag preceding a word in a text string and they are actually able to add a click listener onto that word that launches another activity, does anyone know how this is achieved? below I have attached an example photo showing what i'm trying to achieve, any help would go a long way thanks

enter image description here

Was it helpful?

Solution

Take a look at the Linkify class. It allows you to add Links within you TextViews, for a given regular expression.

The following has been extracted from this article:

TextView mText = (TextView) findViewById(R.id.mytext);
Pattern userMatcher = Pattern.compile("\B@[^:\s]+");
String userViewURL = "user://";
Linkify.addLinks(mText, userMatcher, userViewURL);

Pattern is used to create new pattern from given reguler expression like example above which catch any text like @username in the given text , then you have to define your user:// scheme this also have to be defined in activity which will catch the clicks and last one Linkify.addLinks make all of them work together. Lets look at Android.manifest file for intent filter.

<activity android:name=”.DirectMessageActivity” > 
    <intent-filter>
        <category android:name=”android.intent.category.DEFAULT”/> 
        <action android:name=”android.intent.action.VIEW” /> 
        <data android:scheme=”user” /> 
    </intent-filter> 
</activity>

When you click @username this is the activity that will catch the click and process the clicked string. Yes we didnt mention about what is send to DirectMessageActivity when user click @username , as you might guess “username” string will be passed to DirectMessageActivity. You can get this string like this.

Uri data = getIntent.getData();
if(data != null){
    String uri = data.toString();
    username = uri.substring(uri.indexOf("@")+1);
}

OTHER TIPS

Try it this way.......

TextView tv[] = new TextView[subCategory.length];
    for (int i = 0; i < subCategory.length; i++) {
            tv[i] = new TextView(this);
            tv[i].setText(subCategory[i]);
            tv[i].setId(i);
            sCategoryLayout.addView(tv[i]);
            tv[i].setOnClickListener(onclicklistener);
        }

onclicklistener method :

OnClickListener onclicklistener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if(v == tv[0]){
            //do whatever you want....
        }
    }
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top