android_5 修改一个textview中的字符串的颜色

来源:互联网 发布:手机淘宝店铺首页装修 编辑:程序博客网 时间:2024/06/05 19:42

例:Hello World, 欢迎观看《android教程》哈哈!

要求把《android教程》变红,其他为绿

 

给textView定义一个id,定义id的方法:android:id="@+id/tv"

 

android:autoLink="all" 表示web/mail/map之类的都加链接

 

修改main.xml:

<TextView     android:id="@+id/tv"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:textSize="20sp"    android:textColor="#00ff00"    android:text="@string/say"    />

 

 String.xml:

<?xml version="1.0" encoding="utf-8"?><resources>    <string name="hello">Hello World, TextVitwDemoActivity!</string>    <string name="say">Hello World, 欢迎观看《android教程》哈哈!</string>    <string name="app_name">TextViewDemo</string></resources>

 

TextVitwDemoActivity.java:

package com.mhm.textView;import android.app.Activity;import android.os.Bundle;import android.text.Html;import android.widget.TextView;public class TextVitwDemoActivity extends Activity {    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        TextView tv = (TextView)findViewById(R.id.tv);        String text = tv.getText().toString();        int tb = text.indexOf("《");        int te = text.indexOf("》") + 1;        String text_b = text.substring(0, tb);        String text_m = text.substring(tb, te);        String text_e = text.substring(te, text.length());        tv.setText(Html.fromHtml(text_b + "<font color=red>" + text_m + "</font>" + text_e));    }}

 

 

 

 

也可以这样写:

package com.mhm.textView;import android.R.color;import android.app.Activity;import android.graphics.Color;import android.os.Bundle;import android.text.Html;import android.text.Spannable;import android.text.SpannableStringBuilder;import android.text.style.ForegroundColorSpan;import android.widget.TextView;public class TextVitwDemoActivity extends Activity {    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        TextView tv = (TextView)findViewById(R.id.tv);        String text = tv.getText().toString();        int tb = text.indexOf("《");        int te = text.indexOf("》") + 1;        SpannableStringBuilder style = new SpannableStringBuilder(text);        style.setSpan(new ForegroundColorSpan(Color.GREEN), 0, tb, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);        style.setSpan(new ForegroundColorSpan(Color.RED), tb, te, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);        style.setSpan(new ForegroundColorSpan(Color.GREEN), te, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);        tv.setText(style);    }}

 这里有个奇怪的地方,int te = text.indexOf("》") + 1

+1必须写在这里,写在下面就不行。。。啥原因?

 

 

 

 

  • 大小: 13.5 KB
  • 查看图片附件
原创粉丝点击