TextView中设置不同颜色字体

简单来说,就是直接将字符串转化为html字符,然后让textView显示。
import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.widget.TextView;

public class AndroidFronColorTest extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.main);
        
        TextView text = (TextView)findViewById(R.id.testTextView);
        
        String source = "这只是一个测试,测试下划线斜体字红色字的格式";
 
        text.setText(Html.fromHtml(source));
    }
}
方法二:
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.Spannable;
import android.text.style.BackgroundColorSpan;
import android.text.style.StyleSpan;
import android.widget.EditText;
import android.widget.TextView;

public class AndroidFronColorTest extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.main);
        
        TextView htmlFormateTextView = (TextView)findViewById(R.id.testTextView);
        
        String source = "这只是一个测试,测试下划线斜体字红色字的格式";
 
        htmlFormateTextView.setText(Html.fromHtml(source));
        
        EditText et = (EditText) findViewById(R.id.textView);

        Spannable sp = (Spannable) et.getText();

        sp.setSpan(new BackgroundColorSpan(Color.RED), 0, 5,

        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        sp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), 6, 11,

        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
}

 
  

你可能感兴趣的:(TextView中设置不同颜色字体)