Android在一个TextView里显示不同样式的字体

在同一个TextView里显示不同样式的字体

public void setSpan(Object what, int start, int end, int flags);

样式1:背景色、粗体、字体大小

  • 效果

    P1

  • Code

    TextView textView = (TextView) findViewById(R.id.text_view_font_1);
    Spannable string = new SpannableString("修改背景色、粗体、字体大小");
    // 背景色
    string.setSpan(new BackgroundColorSpan(Color.RED), 2, 5, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    // 粗体
    string.setSpan(new StyleSpan(Typeface.BOLD), 6, 8, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    // 字体大小
    string.setSpan(new AbsoluteSizeSpan(50), 11, 13, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    // 显示
    textView.setText(string);

样式2:斜体加粗

  • 效果

    P2

  • Code

    TextView textView = (TextView) findViewById(R.id.text_view_font_1);
    Spannable string = new SpannableString("Hello TextView");
    // 斜体加粗(中文斜体好像没有什么效果)
    string.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    textView.setText(string);

样式3:字体颜色

  • 效果

    P3

  • Code

    TextView textView = (TextView) findViewById(R.id.text_view_font_1);
    Spannable string = new SpannableString("设置红色字体");
    // 字体颜色
    string.setSpan(new ForegroundColorSpan(Color.RED), 2, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    textView.setText(string);

样式4:下划线

  • 效果

    P4

  • Code

    TextView textView = (TextView) findViewById(R.id.text_view_font_1);
    Spannable string = new SpannableString("带下划线的文字");
    string.setSpan(new URLSpan(""), 1, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    textView.setText(string);

样式5:字体宽度(设置字体宽度比)

  • 效果

    P5

  • Code

    TextView textView = (TextView) findViewById(R.id.text_view_font_1);
    Spannable string = new SpannableString("“胖”文字和“瘦”文字");
    string.setSpan(new ScaleXSpan(2.0f), 1, 2, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    string.setSpan(new ScaleXSpan(0.5f), 7, 8, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    textView.setText(string);

样式6:删除线

  • 效果

    P6

  • Code

    TextView textView = (TextView) findViewById(R.id.text_view_font_1);
    Spannable string = new SpannableString("把“删除”划掉");
    // 删除线
    string.setSpan(new StrikethroughSpan(), 2, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    textView.setText(string);

样式7:前景色

  • 效果

    P7

  • Code

    TextView textView = (TextView) findViewById(R.id.text_view_font_1);
    Spannable string = new SpannableString("设置前景色为红色");
    // 前景色
    string.setSpan(new ForegroundColorSpan(Color.RED), 6, 7, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    textView.setText(string);

样式8:URL

  • 效果

  • Code

    TextView textView = (TextView) findViewById(R.id.text_view_font_1);
    final String contact = "Email: [email protected]\n" +
            "Phone: 188123456789\n" +
            "Fax: +47-12345678\n" +
            "HTTP: http://blog.csdn.net/q4878802";
    textView.setAutoLinkMask(Linkify.ALL); // or set 'android:autoLink' in layout xml
    textView.setText(contact);

你可能感兴趣的:(Android系统控件的使用)