android 为TextView的部分文字设置超链接样式并监听点击事件

package com.example.testandroid1;

import android.app.Activity;
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;
import android.widget.Toast;

public class MainActivity extends Activity {

	private TextView textView;

	private String clickStr1 = "", clickStr2 = "";
	private String str1 = "", str2 = "", str3 = "";
	private int start1 = 0, start2 = 0, end1 = 0, end2 = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		String s = "球队[呼赛测试球队3]邀请[球员2]加入球队";

		textView = (TextView) findViewById(R.id.main_textview);
		textView.setText(getClickableSpan());

		//此行必须有
		textView.setMovementMethod(LinkMovementMethod.getInstance());

	}


	private SpannableString getClickableSpan() {

		//监听器
		View.OnClickListener listener = new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Toast.makeText(MainActivity.this, "Click Success", Toast.LENGTH_SHORT).show();
			}
		};

		SpannableString spanableInfo = new SpannableString("球队[呼赛测试球队3]邀请[球员2]加入球队");
		int start = 2;  //超链接起始位置
		int end = 11;   //超链接结束位置

		//可以为多部分设置超链接
		spanableInfo.setSpan(new Clickable(listener), start, end, Spanned.SPAN_MARK_MARK);
		spanableInfo.setSpan(new Clickable(listener), 14, 18, Spanned.SPAN_MARK_MARK);

		return spanableInfo;
	}
}

	class Clickable extends ClickableSpan implements View.OnClickListener {
		private final View.OnClickListener mListener;

		public Clickable(View.OnClickListener listener) {
			mListener = listener;
		}

		@Override
		public void onClick(View view) {
			mListener.onClick(view);
		}



	/*private void formatData(String s){
		for(int i=0;i<2;i++){
			if (i==0){
				start1 = s.indexOf("[",0);
				end1 = s.indexOf("]",0);
			}else{
				start2 = s.indexOf("[",start1+1);
				end2 = s.indexOf("]",end1+1);
			}
			if (i==0){
				if (start1 > 0){
					clickStr1 = s.substring(start1,end1+1);
				}
			}
			if (i==1){
				if (start2>0){
					clickStr2 = s.substring(start2,end2+1);
				}
			}
		}

		str1 = s.substring(0,start1);
		str2 = s.substring(end1+1,start2);
		str3 = s.substring(end2+1,s.length());
	}*/

}

你可能感兴趣的:(android,textview超链接)