最近项目中遇到一个问题,就是一段文字中股票可点击并跳到股票详情,只记得SpannableString可以实现富文本功能,但并不知道可实现的富文本有点击功能,就开始借助万能搜索引擎,结果不出意料,的确有ClickableSpan这个类可实现点击功能,于是就开始查找Android api ClickableSpan,废话不说了上代码
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView tv = (TextView) findViewById(R.id.text); tv.setText(getClickableSpan()); tv.setMovementMethod(LinkMovementMethod.getInstance());//必须设置否则无效 } private SpannableString getClickableSpan() { View.OnClickListener l = new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, " you are clicking ~", Toast.LENGTH_SHORT).show(); } }; SpannableString spanableInfo = new SpannableString( "This is a test, Click Me"); int start = 16; int end = spanableInfo.length(); spanableInfo.setSpan(new Clickable(l), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); return spanableInfo; } /** * 内部类,用于截获点击富文本后的事件 */ class Clickable extends ClickableSpan implements View.OnClickListener { private final View.OnClickListener mListener; public Clickable(View.OnClickListener mListener) { this.mListener = mListener; } @Override public void onClick(View v) { mListener.onClick(v); } @Override public void updateDrawState(TextPaint ds) { ds.setColor(ds.linkColor); ds.setUnderlineText(false); //去除超链接的下划线 } } }
参考:http://blog.csdn.net/lan410812571/article/details/9083023
http://blog.csdn.net/lan410812571/article/details/9083023