Android TextView 给文本中指定片段添加自定义点击事件

package wq.test;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.TextView;

public class AndroidTestActivity extends Activity
{
	private final String stringToShow = "test,test,test,test,test,test,test,test,test,test,test,test," +
			"test,test,test,test,test,test,test,test,test,test,test,test,test,test" +
			",test,test,test,test,test,test,test,test,test,test,test,test,test,test" +
			"testtest test test...";
	private final String readMore = "Read More";

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.main);
		TextView tv = (TextView) this.findViewById(R.id.textView);
		ClickableSpan clickableSpan = new ClickableSpan() {
			@Override
			public void onClick(View widget) {
				if (widget instanceof TextView) {
					((TextView) widget).setText(stringToShow + stringToShow);
				}
			}
		};
		setClickableSpanForTextView(tv, clickableSpan, stringToShow + readMore, stringToShow.length(), stringToShow.length() + readMore.length());
	}

	/**
	 * 
	 * @param tv TextView
	 * @param clickableSpan Click event
	 * @param text Text to show
	 * @param start Start point in text for handle click event
	 * @param end End point in text for handle click event
	 */
	private void setClickableSpanForTextView(TextView tv, ClickableSpan clickableSpan, String text, int start, int end) {
		SpannableString sp = new SpannableString(text);
		sp.setSpan(clickableSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		tv.setText(sp);
		tv.setLinkTextColor(Color.RED);
		tv.setMovementMethod(LinkMovementMethod.getInstance());
		tv.setFocusable(false);
		tv.setClickable(false);
		tv.setLongClickable(false);
	}
}

你可能感兴趣的:(java,android)