对于TextView某些字符设置点击事件和改变颜色

将TextView的某些字符设置点击事件和设置背景色,主要用到SpannableString这个类,下面贴上写的代码
/**
		 * 为项目名称,申请人姓名设置点击事件
		 * @param str
		 * @param position
		 * @param flag
		 * @return
		 */
		private SpannableString getClickableSpan(String str,final int position){
			final View.OnClickListener l=new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Toast.makeText(getActivity(), "点击", 0).show();
					Intent intent=new Intent(getActivity(),ProjectDetailActivity.class);
					intent.putExtra("projectId",(Integer)items.get(position).get(0));
					intent.putExtra("projectName", items.get(position).get(1).toString());
					intent.putExtra("projectNeed", items.get(position).get(2).toString());
					intent.putExtra("projectContent", items.get(position).get(3).toString());
					intent.putExtra("publishTime", items.get(position).get(5).toString());
					intent.putExtra("id",(Integer)items.get(position).get(6));
					startActivity(intent);
				}
			};
			final View.OnClickListener l2=new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Toast.makeText(getActivity(), "点击2", 0).show();
					Intent intent=new Intent(getActivity(),OthersInfoActivity.class);
					intent.putExtra("_userEmail", items.get(position).get(8).toString());
					startActivity(intent);
				}
			};
			String name=items.get(position).get(7).toString();
			 SpannableString spnableInfo=new SpannableString(name+"申请加入"+str+"项目");
			int start=name.length()+4;
			int end=name.length()+4+str.length();
			int start2=0;
			int end2=name.length();
			
			spnableInfo.setSpan(new ClickableSpan() {
				@Override
				public void onClick(View widget) {
					// TODO Auto-generated method stub
					l.onClick(widget);
				}
			}, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			spnableInfo.setSpan(new ForegroundColorSpan(Color.RED), start, end,  Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			spnableInfo.setSpan(new ClickableSpan() {
				@Override
				public void onClick(View widget) {
					// TODO Auto-generated method stub
					l2.onClick(widget);
				}
			}, start2, end2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			spnableInfo.setSpan(new ForegroundColorSpan(Color.RED), start2, end2,  Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			return spnableInfo;
		}
		

然后在TextView的设置中调用这个方法就行了

tv.setText(getClickableSpan(projectName,position));
tv.setMovementMethod(LinkMovementMethod.getInstance());

在此记录一下...

你可能感兴趣的:(对于TextView某些字符设置点击事件和改变颜色)