javaandroiduiscrollviewspannablestringclickablespan

Problem with SpannableString and ClickableSpan


I wrote this code:

public class BaldrActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.a_dei_baldr);

    String myString = "Click Here!";

    SpannableString ss = new SpannableString(myString);

    ClickableSpan clickableSpan1 = new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            Toast.makeText(BaldrActivity.this, "hello world", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setColor(Color.BLUE);
            ds.setUnderlineText(false);
        }
    };

    ss.setSpan(clickableSpan1, 6, 11, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    TextView tv = findViewById(R.id.tv_baldr1);
    tv.setText(myString);
    tv.setMovementMethod(LinkMovementMethod.getInstance());
}

}

but... nothing changes. I mean, the code is builded correctly, the app does not crash, the TextView actually changes in "Click Here!", but it is not clickable and its appereance does not change... why?


Solution

  • Looks like you are setting String in line:

    tv.setText(myString);
    

    instead, set SpannableString that you are creating:

    tv.setText(ss);