SpannableString 和 ClickableSpan 的问题
Problem with SpannableString and ClickableSpan
我写了这段代码:
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());
}
}
但是...没有任何变化。我的意思是,代码构建正确,应用程序没有崩溃,TextView 实际上在 "Click Here!" 中发生了变化,但它不可点击且其外观没有变化...为什么?
看起来您在行中设置字符串:
tv.setText(myString);
相反,设置您正在创建的 SpannableString:
tv.setText(ss);
我写了这段代码:
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());
}
}
但是...没有任何变化。我的意思是,代码构建正确,应用程序没有崩溃,TextView 实际上在 "Click Here!" 中发生了变化,但它不可点击且其外观没有变化...为什么?
看起来您在行中设置字符串:
tv.setText(myString);
相反,设置您正在创建的 SpannableString:
tv.setText(ss);