(原創)代碼動態改變某些textview文本顏色及其大小的方式

(原創)代碼動態改變某些textview文本顏色及其大小的方式

1.以下示例將Hello Word!中的ell改變紅色並改變大小:

效果圖:

package com.example.lainanzhou.textviewdemo;

import android.app.Activity;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.TextAppearanceSpan;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = (TextView) findViewById(R.id.tv);
        String str = textView.getText().toString().trim();//"Hello World!":下面將前面Hello中的ell變紅
        ColorStateList colors = ColorStateList.valueOf(0xffff0000);//轉換相應的color值,這裏是紅色值
        SpannableString spanBuilder = new SpannableString(str);
        /**
         * 參數:1.變化字體參數(1.字體類型;2.字體樣式;3.需要變化字體大小;4.顏色值;5.顏色關聯狀態)
         *      2.變化起始位置(含)
         *      3.變化結束位置(不含)~例如Hello中ell是從1角標開始到4結束,不含4角標在內
         *      4.標記
         */
        spanBuilder.setSpan(new TextAppearanceSpan(null, 0, dip2px(24), colors, null),
                1, 4, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        textView.setText(spanBuilder);
    }

    private int dip2px(float dipValue) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }
}

源碼下載地址:點擊打開鏈接
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章