1. 程式人生 > >獲取一段文字中的某一串並標記成URL,SpannableStringBuilder

獲取一段文字中的某一串並標記成URL,SpannableStringBuilder

public CharSequence getClickableHtml(String html) {
		Spanned spannedHtml = Html.fromHtml(html);
		SpannableStringBuilder clickableHtmlBuilder = new SpannableStringBuilder(spannedHtml);
		URLSpan[] urls = clickableHtmlBuilder.getSpans(0, spannedHtml.length(), URLSpan.class);
		for (final URLSpan span : urls) {
			setLinkClickable(clickableHtmlBuilder, span);
		}
		return clickableHtmlBuilder;
	}

	private void setLinkClickable(final SpannableStringBuilder clickableHtmlBuilder, final URLSpan urlSpan) {
		int start = clickableHtmlBuilder.getSpanStart(urlSpan);
		int end = clickableHtmlBuilder.getSpanEnd(urlSpan);
		int flags = clickableHtmlBuilder.getSpanFlags(urlSpan);
		ClickableSpan clickableSpan = new ClickableSpan() {
			public void onClick(View view) {
				// Do something with URL here.
				if (!TextUtils.isEmpty(urlSpan.getURL())) {
					int result = urlSpan.getURL().indexOf("tel");
					int result2 = urlSpan.getURL().indexOf("http");
					if (result >= 0) {
						Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(urlSpan.getURL()));
						MessageDetailsActivity.this.startActivity(intent);// 內部類
					} else if (result2 >= 0) {
						Intent intent = new Intent(MessageDetailsActivity.this, ShipWayArrivedExcDetailActivity.class);
						intent.putExtra("title", "訂單詳情");
						intent.putExtra("orderId", messageInfo.getCustomerOrderNo());
						intent.putExtra("url", urlSpan.getURL());
						startActivity(intent);
					}
				}

			}

		};
		clickableHtmlBuilder.setSpan(clickableSpan, start, end, flags);
	}