1. 程式人生 > >Android TextView部分字型變色或字型變大小

Android TextView部分字型變色或字型變大小

A. 

SpannableStringBuilder style=new SpannableStringBuilder(str);
//SpannableStringBuilder實現CharSequence介面
style.setSpan(new ForegroundColorSpan(Color.RED), 0, 2,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE );
style.setSpan(new ForegroundColorSpan(Color.YELLOW), 2, 4,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE );
style.setSpan(new ForegroundColorSpan(Color.GREEN), 4, 6,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE );
tv.setText(style);//將其新增到tv中 

String html = "預計收益<font color='#ff0000'>"+et_buy_sum.getText().toString()+"</font>";
tv_profit_think.setText(Html.fromHtml(html));

B

TextView textView1 = (TextView) findViewById(R.id.textView1);
        TextView textView2 = (TextView) findViewById(R.id.textView2);
        TextView textView3 = (TextView) findViewById(R.id.textView3);
        TextView textView4 = (TextView) findViewById(R.id.textView4);

        //兩次加大字型,設定字型為紅色(big會加大字號,font可以定義顏色)
        textView1.setText(Html.fromHtml("北京市釋出霾黃色預警,<font color='#ff0000'><big><big>外出攜帶好</big></big></font>口罩"));

        //設定字型大小為3級標題,設定字型為紅色
        textView2.setText(Html.fromHtml("北京市釋出霾黃色預警,<h3><font color='#ff0000'>外出攜帶好</font></h3>口罩"));

        //設定字型大小為58(單位為物理畫素),設定字型為紅色,字型背景為黃色
        textView3.setText("北京市釋出霾黃色預警,外出攜帶好口罩");
        Spannable span = new SpannableString(textView3.getText());
        span.setSpan(new AbsoluteSizeSpan(58), 11, 16, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new ForegroundColorSpan(Color.RED), 11, 16, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new BackgroundColorSpan(Color.YELLOW), 11, 16, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView3.setText(span);

        //兩次縮小字型,設定字型為紅色(small可以減小字號)
        textView4.setText(Html.fromHtml("北京市釋出霾黃色預警,<font color='#ff0000'><small><small>外出攜帶好</small></small></font>口罩"));