texeview設置不同文字的點擊事件

package com.example.demo;


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


public class DemoActivity extends Activity {


private TextView tv;


@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
tv = (TextView) findViewById(R.id.tv_demo);


tv.setText("這是測試DEMO");
SpannableString s1 = new SpannableString("點擊點擊 ");
s1.setSpan(new Clickable1(), 0, "點擊點擊".length(),
Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
tv.append(s1);


tv.append("-----------分割線----------");


SpannableString s2 = new SpannableString("點擊點擊 ");
s2.setSpan(new Clickable2(), 0, "點擊點擊".length(),
Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
tv.append(s2);


tv.append("***********");
tv.setMovementMethod(LinkMovementMethod.getInstance());
}


private class Clickable1 extends ClickableSpan {


@Override
public void updateDrawState(TextPaint ds) {


ds.setColor(getResources().getColor(R.color.green));
ds.setUnderlineText(false); // 去掉下劃線
}


@Override
public void onClick(View v) {


Toast.makeText(DemoActivity.this, "Clickable11111",
Toast.LENGTH_SHORT).show();
}


}


private class Clickable2 extends ClickableSpan {


@Override
public void updateDrawState(TextPaint ds) {


ds.setColor(getResources().getColor(R.color.red));
ds.setUnderlineText(false); // 去掉下劃線
}


@Override
public void onClick(View v) {


Toast.makeText(DemoActivity.this, "Clickable22222",
Toast.LENGTH_SHORT).show();
}


}


}





下面是佈局文件Textview的 android:clickable="true"要設爲true




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >


    <TextView
        android:clickable="true"
        android:id="@+id/tv_demo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="22sp" />


</LinearLayout>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章