Android中点击TextView文本链接跳转到指定页面

来源:互联网 发布:江苏教师网络培训平台 编辑:程序博客网 时间:2024/04/29 06:26

最近由于公司业务需求,需要在一段文本中识别出带有超链接的文本,点击跳转到指定页面,于是就在网上查找资料,主要涉及到的技术点有:TextView正则匹配、文本链接、点击链接页面跳转。

代码如下:

public class MainActivity extends AppCompatActivity {    SpannableStringBuilder ssb;    private TextView content;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        requestWindowFeature(Window.FEATURE_NO_TITLE);        setContentView(R.layout.activity_main);        content = (TextView)findViewById(R.id.content);        content.setText(checkAutoLink());        content.setMovementMethod(LinkMovementMethod.getInstance());    }    private CharSequence checkAutoLink() {        String content = getResources().getString(R.string.content);        ssb = new SpannableStringBuilder(content);        Pattern pattern = Pattern.compile("使用条款");//根据正则匹配出带有超链接的文字        Matcher matcher = pattern.matcher(ssb);        while (matcher.find()) {            setClickableSpan(ssb, matcher);        }        return ssb;    }    private void setClickableSpan(final SpannableStringBuilder clickableHtmlBuilder, final Matcher matcher) {        int start = matcher.start();        int end = matcher.end();        final String url = "http://www.baidu.com";        ClickableSpan clickableSpan = new ClickableSpan() {            public void onClick(View view) {                gotoUrl(url);//点击超链接时调用            }            @Override            public void updateDrawState(TextPaint ds) {                ds.setUnderlineText(false);//当传入true时超链接下会有一条下划线            }        };        //设置超链接文本的颜色        ssb.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorAccent)),start,end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);        clickableHtmlBuilder.setSpan(clickableSpan, start, end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE); }    private void gotoUrl(String url){        //实现跳转逻辑    }}
如有更好的方法意见,望指点。

0 0
原创粉丝点击