第1部分:概述
平常在开发当中可能会遇到一些情况,需要一个文本框显示不同样式的字体。当然,你也可以选择用多个文本框来显示,只不过需要多设置几次。我在做项目的时候也遇到这样的需求,自己对TextView进行了一个扩展,基本可以实现功能。
第2部分:示例图片
图片示例:
第3部分:代码示例
1. 自定义View
import android.content.Context;import android.text.SpannableString;import android.text.Spanned;import android.text.TextUtils;import android.text.style.TextAppearanceSpan;import android.util.AttributeSet;import android.widget.TextView;public class MutiColorTextView extends TextView {public MutiColorTextView(Context context) {super(context);}public MutiColorTextView(Context context, AttributeSet attrs) {super(context, attrs);}public MutiColorTextView(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);}/*** 将一串字符中的一部分改变字体样式** @param context* @param originStr 本来的字符串* @param formatStr 需要改变的字符串* @param normalStyle 整体的字体样式* @param emphasizeStyle 需要改变部分的字体样式* @return*/public boolean setTextStyle(Context context, String originStr, String formatStr, int normalStyle, int emphasizeStyle) {if (!TextUtils.isEmpty(originStr) && !TextUtils.isEmpty(formatStr)) {try {int formatStart = originStr.indexOf(formatStr);int formatlength = formatStr.length();SpannableString formatString = new SpannableString(originStr);formatString.setSpan(new TextAppearanceSpan(context, normalStyle), 0, originStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);formatString.setSpan(new TextAppearanceSpan(context, emphasizeStyle), formatStart, formatStart + formatlength, Spanned.SPAN_INCLUSIVE_INCLUSIVE);setText(formatString);return true;} catch (Exception e) {e.printStackTrace();return false;}} else {return false;}}}
2. style 代码
<style name="order_remark_normal"><item name="android:textColor">#999999</item></style><style name="order_remark_emphasize"><item name="android:textColor">#ea3640</item></style>
3. 调用
textView.setTextStyle(mContext, "你好吗,哈哈哈哈,我很好", "哈哈哈哈", R.style.order_remark_normal, R.style.order_remark_emphasize)