main.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="期望有一天不用写代码也可以吃得起馒头" /> </RelativeLayout>
mainActivity如下:
package c.c; import android.app.Activity; import android.os.Bundle; import android.text.Spannable; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; import android.text.style.URLSpan; import android.view.View; import android.widget.TextView; import android.widget.Toast; /** * Demo描述: * 为TextView中的文字设置链接,当点击此链接的时候执行相应的操作 */ public class MainActivity extends Activity { private TextView mTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } private void init() { mTextView=(TextView) findViewById(R.id.textView); String string = mTextView.getText().toString(); addUrlSpan(mTextView, string); mTextView.setFocusable(true); mTextView.setMovementMethod(LinkMovementMethod.getInstance()); catchUrl(mTextView); } private class TestSpan extends ClickableSpan { private String url; TestSpan(String url) { this.url = url; } @Override public void onClick(View widget) { if (url.equals("showinfo")) { Toast.makeText(MainActivity.this, "点击了链接", Toast.LENGTH_SHORT).show(); System.out.println("执行点击链接后的操作"); } } } private void addUrlSpan(TextView tv, String string) { SpannableString spanString = new SpannableString(string); URLSpan span = new URLSpan("showinfo"); int start = string.length() - 4; int end = string.length() - 1; spanString.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); tv.setText(spanString); } private void catchUrl(TextView textView) { CharSequence text = textView.getText(); if (text instanceof Spannable) { int end = text.length(); Spannable sp = (Spannable) textView.getText(); URLSpan[] urls = sp.getSpans(0, end, URLSpan.class); SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text); spannableStringBuilder.clearSpans(); for (URLSpan url : urls) { TestSpan testSpan = new TestSpan(url.getURL()); spannableStringBuilder.setSpan(testSpan, sp.getSpanStart(url), sp.getSpanEnd(url), Spannable.SPAN_EXCLUSIVE_INCLUSIVE); } textView.setText(spannableStringBuilder); } } }
时间: 2024-10-07 20:39:33