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

前端 未结 7 2133
忘掉有多难
忘掉有多难 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 00:37

    //Got But Without Pattern Match

        SpannableString hashText = new SpannableString("I just watched #StarWars and it was incredible. It's a #MustWatch #StarWars");
    
    
    
        ClickableSpan clickableSpanstar1stWarsHashText = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                //Intent starWars = new Intent(MainActivity.this,starWars.class); //starWars is a class file which extends Activity
                //startActivity(starWars);
                Toast.makeText(MainActivity.this,"Clicked On 1st #StarWars Remove comments of above line",Toast.LENGTH_LONG).show();
            }
        };
    
        ClickableSpan clickableSpanmustWatchHashText = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                //Intent mustWatch = new Intent(MainActivity.this,mustWatch.class); //starWars is a class file which extends Activity
                //startActivity(mustWatch);
                Toast.makeText(MainActivity.this,"Clicked On #MustWatch Remove comments of above line",Toast.LENGTH_LONG).show();
            }
        };
    
        ClickableSpan clickableSpanstar2ndWarsHashText = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                //Intent starWars = new Intent(MainActivity.this,starWars.class); //starWars is a class file which extends Activity
                //startActivity(starWars);
                Toast.makeText(MainActivity.this,"Clicked On 2nd #StarWars Remove comments of above line",Toast.LENGTH_LONG).show();
            }
        };
    
        hashText.setSpan(clickableSpanstar1stWarsHashText,15,24, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        hashText.setSpan(clickableSpanmustWatchHashText, 55, 65, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        hashText.setSpan(clickableSpanstar2ndWarsHashText,66,75, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    
    
    
    
        //SpannableString hashText = new SpannableString("I just watched #StarWars and it was incredible. It's a #MustWatch #StarWars");
    
        TextView  textView = (TextView) findViewById(R.id.textView); //textView id i.e. android:id="@+id/textView"
        textView.setText(hashText);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
        textView.setHighlightColor(Color.TRANSPARENT);
    

提交回复
热议问题