android中TextView同一行显示不同颜色文字

来源:互联网 发布:cp linux 复制目录 编辑:程序博客网 时间:2024/06/09 20:23


方法一:利用html

import android.app.Activity;import android.os.Bundle;import android.text.Html;import android.widget.TextView;public class MainActivity extends Activity {/** 利用HTML语言,改变文字颜色 */private void init() {String str = "<font color='red'>中软</font>"+ "<font color= 'green'>国际</font>";TextView tv = new TextView(this);tv.setText(Html.fromHtml(str));}@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);init();}}

方法二:

转载自:http://blog.csdn.net/centralperk/article/details/8674599

    textView = (TextView) findViewById(R.id.textview);      SpannableStringBuilder builder = new SpannableStringBuilder(textView.getText().toString());            //ForegroundColorSpan 为文字前景色,BackgroundColorSpan为文字背景色      ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED);      ForegroundColorSpan whiteSpan = new ForegroundColorSpan(Color.WHITE);      ForegroundColorSpan blueSpan = new ForegroundColorSpan(Color.BLUE);      ForegroundColorSpan greenSpan = new ForegroundColorSpan(Color.GREEN);      ForegroundColorSpan yellowSpan = new ForegroundColorSpan(Color.YELLOW);                        builder.setSpan(redSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);      builder.setSpan(whiteSpan, 1, 2, Spannable.SPAN_INCLUSIVE_INCLUSIVE);      builder.setSpan(blueSpan, 2, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);      builder.setSpan(greenSpan, 3, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);      builder.setSpan(yellowSpan, 4,5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);            textView.setText(builder);  


0 0