爲TextView設置不同的字體大小和顏色



問題描述:有時候需要爲一個TextView設置不同的顏色和字體大小,這是怎麼辦呢?

問題解答:

  1. 首先先在styles.xml文件中定義你需要的樣式,可以設置大小、顏色等。如:

<style name="style0">

    <item name="android:textSize">20sp</item>

    <item name="android:textColor">@color/black</item>

</style>



<style name="style1">

    <item name="android:textSize">17sp</item>

    <item name="android:textColor">@color/gray</item>

</style>
  1. 在代碼中添加如下代碼:

if (goods.getPack()!=null&&!goods.getPack().isEmpty()){

    //TextView設置不同的字體大小和顏色

    SpannableString styledText = new SpannableString(goods.getName()+"  "+goods.getPack());

    styledText.setSpan(new TextAppearanceSpan(mContext, R.style.style0), 0, goods.getName().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    styledText.setSpan(new TextAppearanceSpan(mContext, R.style.style1), goods.getName().length()+2, goods.getName().length()+goods.getPack().length()+2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    name.setText(styledText, TextView.BufferType.SPANNABLE);

}else{

    name.setText(goods.getName());

}

 

 

 

 

 

如果你只是需要設置文字的樣色,可以考慮使用html

/**

 * 採用HTML爲標題設置不同顏色

 * @param pack 包裝

 * @param name 產品名

 * @return

 */

private String getColorString(String name,String pack){

    return "<font color=\"#323232\">" + name + "</font>"+"<font color=\"#939393\" font-size:10px>" + pack + "</font>" ;

}

調用方法設置字體顏色

name.setText(Html.fromHtml(getColorString(goods.getName(),goods.getPack())));

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章