Android: Setting onClickListener to a Part of text in a TextView - Issue

前端 未结 7 2134
忘掉有多难
忘掉有多难 2021-01-03 23:57

I am trying to recognise hashtags in my TextView and make them clickable such that I can take the user to another View when they click on the Hashtag.

I managed to i

相关标签:
7条回答
  • 2021-01-04 01:03

    You can achieve it by using split function and populate textview's in a Layout like this :

     layout=(LinearLayout)findViewById(R.id.layout);
     String data="I just watched #StarWars and it was incredible. It's a #MustWatch #StarWars";
    TextView textView;
         String [] s=data.split(" ");
         for(int i=0;i<s.length;i++){
             if(s[i].matches("#([A-Za-z0-9_-]+)")){
    
                  textView=new TextView(this);
                  textView.setText(s[i]);
                  textView.setTextColor(Color.parseColor("#000763"));
                  textView.setTag(s[i]);
                  textView.setOnClickListener(viewClicked(textView));
             }else{
                 textView=new TextView(this);
                  textView.setText(" "+s[i]);
             }
             layout.addView(textView,i);
         }
    

    and a Method to handle click event to required Textview's :

     View.OnClickListener viewClicked(final TextView textView)  {
        return new View.OnClickListener() {
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), v.getTag().toString(), 1000).show();
    
            }
        };
    }
    
    0 讨论(0)
提交回复
热议问题