通过
SpannableStringBuilder style = new SpannableStringBuilder(CharSequence cs);
style.setSpan(new ForegroundColorSpan(color), begin, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(style);
设置,由于此种方法比较复杂,我实现了一个辅助类,能够快速实现部分字体的颜色;
final class TextViewUtil{ public static CharSequence setTextColor(CharSequence str,int begin,int end,int color){ SpannableStringBuilder style = new SpannableStringBuilder(str); style.setSpan(new ForegroundColorSpan(color), begin, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return style; } }
package org.xiazdong; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.style.ForegroundColorSpan; import android.widget.TextView; public class MainActivity extends Activity { private TextView tv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv = (TextView)findViewById(R.id.tv); String str = "hello,xiazdong"; CharSequence cq = TextViewUtil.setTextColor(str, 0, 2, Color.RED); cq = TextViewUtil.setTextColor(cq, 2, 5, Color.GREEN); tv.setText(cq); } }
在main.xml布局文件的<TextView>中设置如下:
android:singleLine="true" android:focusable="true" android:ellipsize="marquee" android:marqueeRepeatLimit="marquee_forever" android:focusableInTouchMode="true"
在<TextView>中设置如下:
android:autolink="all",则如果TextView中字符串为“hello,xiazdong's blog:http://blog.csdn.net/xiazdong, phone:12345678901”
则会自动识别 http://blog.csdn.net/xiazdong和12345678901;