Clickable words inside of TextView Android [duplicate]

。_饼干妹妹 提交于 2019-12-30 11:04:51

问题


I have a textview that contains hashtags ex. #first #second #third. My question is how can I detect which hashtag is clicked so I can perform some action - eg. make toast of the word. Is this possible using TextView widget? Should I use some other widget istead?

UPDATE

I found my solution using this example. Hope it will help others in the future!


回答1:


You can use spannable string to achieve this:

SpannableString ss = new SpannableString("Your string");
String[] words = ss.split(" ");
for(final String word : words){
   if(word.startsWith("#")){
     ClickableSpan clickableSpan = new ClickableSpan() {
    @Override
    public void onClick(View textView) {
        //use word here to make a decision 
    }
    };
    ss.setSpan(clickableSpan, ss.indexOf(word), ss.indexOf(word) + word.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  }
}


TextView textView = (TextView) findViewById(R.id.hello);
textView.setText(ss);
textView.setMovementMethod(LinkMovementMethod.getInstance());


来源:https://stackoverflow.com/questions/25363310/clickable-words-inside-of-textview-android

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