关闭

texeview设置不同文字的点击事件

标签: AndroidTextView点击事件
95人阅读 评论(0) 收藏 举报
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>

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2853次
    • 积分:159
    • 等级:
    • 排名:千里之外
    • 原创:12篇
    • 转载:8篇
    • 译文:0篇
    • 评论:1条
    文章分类
    最新评论