1.设置TextView的autoLink属性值
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/text_main_webBaidu" android:autoLink="web"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/text_main_telBaidu" android:autoLink="phone"/> </LinearLayout>
2.识别html代码
<TextView android:id="@+id/tvHtml" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<span style="white-space:pre"> </span>// html识别链接 tvHtml = (TextView) findViewById(R.id.tvHtml); String value = "<html><a href='http://www.baidu.com'>百度一下</a>(注意这里的URL地址必须加http:协议)<br />" + "联系方式:<a href='tel://010-59928888'>010-59928888</a></html>"; // 若打开,与html识别起冲突 // tvHtml.setAutoLinkMask(Linkify.ALL); tvHtml.setMovementMethod(LinkMovementMethod.getInstance()); tvHtml.setText(Html.fromHtml(value));
3.SpannableStringBuilder手动设置连接
<TextView android:id="@+id/tvSpan" android:layout_width="wrap_content" android:layout_height="wrap_content" />
// span手动识别链接 tvSpan = (TextView) findViewById(R.id.tvSpan); value = "[百度一下]\r\n客服电话:[010-59928888]"; // 若打开,仍起作用 // tvSpan.setAutoLinkMask(Linkify.ALL); tvSpan.setMovementMethod(LinkMovementMethod.getInstance()); SpannableStringBuilder builder = new SpannableStringBuilder(value); int indexStart = value.indexOf("["); int indexEnd = 0; while (indexStart != -1) { indexEnd = value.indexOf("]", indexStart); builder = builder.delete(indexEnd, indexEnd + 1); builder = builder.delete(indexStart, indexStart + 1); indexEnd--; value = builder.toString(); final String temp = value.substring(indexStart, indexEnd); if (temp.equals("百度一下")) { builder.setSpan(new ClickableSpan() { @Override public void onClick(View widget) { Toast.makeText(MainActivity.this, temp, Toast.LENGTH_SHORT).show(); String url = "http://www.baidu.com"; Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } }, indexStart, indexEnd, 0); } if (temp.equals("010-59928888")) { builder.setSpan(new ClickableSpan() { @Override public void onClick(View widget) { String url = "tel://010-59928888"; Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); Toast.makeText(MainActivity.this, temp, Toast.LENGTH_SHORT).show(); } }, indexStart, indexEnd, 0); } indexStart = value.indexOf("[", indexEnd); } tvSpan.setText(builder, BufferType.SPANNABLE);
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-01 17:06:12