【问题标题】:Clickable words inside of TextView Android [duplicate]TextView Android内部的可点击单词[重复]
【发布时间】:2014-10-11 08:48:09
【问题描述】:

我有一个包含主题标签的文本视图。 #first #second #third。我的问题是如何检测点击了哪个主题标签,以便我可以执行一些操作 - 例如。祝酒词。 这可以使用 TextView 小部件吗?我应该改用其他小部件吗?

更新

我使用this example 找到了我的解决方案。希望以后能对其他人有所帮助!

【问题讨论】:

    标签: java android android-widget textview android-textattributes


    【解决方案1】:

    您可以使用 spannable string 来实现:

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

    【讨论】:

    • 感谢@vipul 并且要获得点击的单词,您可以在 onClick 中使用它: Spanned sp = (Spanned) ((TextView)textView).getText(); int start = sp.getSpanStart(this); int end = sp.getSpanEnd(this); String word = sp.subSequence(start, end).toString();
    • SpannableString 没有 splitindexOf 方法
    猜你喜欢
    • 2012-04-15
    • 2019-06-14
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多