1.描述
一个TextView ,显示的文本 ,有部分文字被点击后响应事件 ,通过SpannableStringBuilder 实现 。
效果演示 :
2.实现步骤
(1)布局实现
<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"
android:gravity="center"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableRight="@color/bai"
android:drawablePadding="3dp"
android:padding="5px"
android:textSize="30sp"
android:text="HI Spannable" />
</RelativeLayout>
(2)代码实现
注意事项 : 1) 继承 ClickableSpan 实现 View.OnClickListener 接口
2) tv.setMovementMethod(LinkMovementMethod.getInstance()); 必须实现,否则没效果
package cn.labelnet.mytestandrid;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private TextView tv;
private final String TEXT_STRING = "我是百度,我怕谁!?";
private final String TEXT_KEY = "百度";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int startIndex = TEXT_STRING.indexOf(TEXT_KEY);
int endIndex = startIndex + TEXT_KEY.length();
SpannableStringBuilder builder = new SpannableStringBuilder(TEXT_STRING);
// 可单独文本前景色
// builder.setSpan(new ForegroundColorSpan(Color.RED), startIndex,
// endIndex, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
//设置文本点击事件
builder.setSpan(new ClickSpannable(this), startIndex, endIndex,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv = (TextView) findViewById(R.id.tv);
tv.setMovementMethod(LinkMovementMethod.getInstance());
tv.setText(builder);
}
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "我被点击了", Toast.LENGTH_SHORT)
.show();
}
/**
* SpannableStringBuilder 点击事件
*/
private class ClickSpannable extends ClickableSpan implements
OnClickListener {
private View.OnClickListener onClickListener;
public ClickSpannable(View.OnClickListener onClickListener) {
this.onClickListener = onClickListener;
}
@Override
public void onClick(View widget) {
onClickListener.onClick(widget);
}
}
}
3.其它例子