How to add click listeners into a string in Android/Java Textview?

偶尔善良 提交于 2020-01-13 20:00:28

问题


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


回答1:


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);
}



回答2:


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....
        }
    }
};


来源:https://stackoverflow.com/questions/13442144/how-to-add-click-listeners-into-a-string-in-android-java-textview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!