public class MainActivity extends AppCompatActivity {
private TextView tv1 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById( R.id.tv1 );
String url1 = "这是测试";
String url2 = "点击一下试试看";
String url = url1 + url2;
SpannableStringBuilder style = new SpannableStringBuilder(url1 + url2);
TextViewURLSpan myURLSpan = new TextViewURLSpan();
style.setSpan(myURLSpan, url1.length(), url.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
style.setSpan(new StyleSpan(Typeface.NORMAL ), url1.length(), url.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
style.setSpan(new UnderlineSpan(), url1.length(), url.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
style.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimaryDark)), url1.length(), url.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// style.setSpan(new BackgroundColorSpan(getResources().getColor(R.color.colorAccent)), url1.length(),url.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv1.setText(style);
//设置超链接为可点击状态
tv1.setMovementMethod(LinkMovementMethod.getInstance());
}
class TextViewURLSpan extends ClickableSpan {
@Override
public void updateDrawState(TextPaint ds) {
ds.setColor(getResources().getColor(R.color.colorAccent));
ds.setUnderlineText(false); //去掉下划线
}
@Override
public void onClick(View widget) {//点击事件
Toast.makeText( MainActivity.this, "点击了", Toast.LENGTH_SHORT).show();
}
}
}
textview 中间的字变色并可点击
最新推荐文章于 2020-12-19 22:43:48 发布