首页 > 代码库 > Android--TextView第一个单词大写

Android--TextView第一个单词大写

自定义TextView:

public class FirstBoldTextView extends TextView{    private boolean firstWordBold = false;    private String str;    public FirstBoldTextView(Context context, AttributeSet attrs, int defStyle)    {        super(context, attrs, defStyle);        // TODO Auto-generated constructor stub    }    public FirstBoldTextView(Context context, AttributeSet attrs)    {        super(context, attrs);        // TODO Auto-generated constructor stub    }    public FirstBoldTextView(Context context)    {        super(context);    }    @SuppressLint("DrawAllocation")    @Override    protected void onDraw(Canvas canvas)    {        str = getText().toString().trim();        if (!TextUtils.isEmpty(str) && !firstWordBold)        {            SpannableStringBuilder ssb = new SpannableStringBuilder(str);            ssb.setSpan(new FirstWordBoldSpan(Typeface.NORMAL), 0, str.indexOf(" "), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);            setText(ssb);            setMovementMethod(LinkMovementMethod.getInstance());            firstWordBold = true;        }        super.onDraw(canvas);    }        @Override    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter)    {        super.onTextChanged(text, start, lengthBefore, lengthAfter);        firstWordBold = false;    }}

其中FirstWordBoldSpan代码如下:

public class FirstWordBoldSpan extends StyleSpan{    public FirstWordBoldSpan(int style)    {        super(style);    }    @Override    public int describeContents()    {        // TODO Auto-generated method stub        return super.describeContents();    }    @Override    public int getSpanTypeId()    {        return super.getSpanTypeId();    }    @Override    public int getStyle()    {        return super.getStyle();    }    @Override    public void updateDrawState(TextPaint ds)    {        ds.setFakeBoldText(true);        super.updateDrawState(ds);    }    @Override    public void updateMeasureState(TextPaint paint)    {        paint.setFakeBoldText(true);        super.updateMeasureState(paint);    }    @Override    public void writeToParcel(Parcel dest, int flags)    {        // TODO Auto-generated method stub        super.writeToParcel(dest, flags);    }}

 

Android--TextView第一个单词大写