android设置不同文字的点击事件,Android TextView 高亮字体并添加点击事件

运行效果

1dc2e5b7a0fe4b26ca32cf55339d0131.png

package com.zutil.lib;

import android.graphics.Typeface;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.text.Spannable;

import android.text.SpannableStringBuilder;

import android.text.Spanned;

import android.text.TextPaint;

import android.text.method.LinkMovementMethod;

import android.text.style.ClickableSpan;

import android.text.style.ForegroundColorSpan;

import android.text.style.StyleSpan;

import android.text.style.UnderlineSpan;

import android.view.View;

import android.widget.TextView;

import android.widget.Toast;

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();

}

}

}

https://www.cnblogs.com/zhaoyanjun/category/684868.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值