1. 程式人生 > >android TextView 首行縮排與部分文字改變顏色大小效果

android TextView 首行縮排與部分文字改變顏色大小效果

  1. TextView 首行偽縮排效果

    // 原理, 使用Spannable 把前兩個字設定為透明狀態. 雖然是偽縮排, 但是不會因為解析度的不同而產生各種問題, 注意如果
    // TextView設定了可複製的話要再做處理, 否則會把透明的文字也複製了.
    
    Spannable span = new SpannableString("縮排" + customerInfo.getDescription());
    
    span.setSpan(new ForegroundColorSpan(Color.TRANSPARENT), 0, 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    
    mBusiness_scope.setText(span);
    
  2. TextView 部分文字改變顏色大小效果

    String msg = "一行中包含了特殊文字";
    Spannable span = new SpannableString(msg);
    String special = "特殊文字";
    int start = msg.indexOf(special);
    int end = start + special.length();
    // 改變大小 (16為文字大小)
    span.setSpan(new AbsoluteSizeSpan(dip2px(16)), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    // 改變顏色 (Color.YELLOW 為文字顏色)
    span.setSpan(new ForegroundColorSpan(Color.YELLOW), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    TextView.setText(span);
    
    /**
     * dip----to---px
     * @return
     */
    public static int dip2px(int dip) {
        // 縮放比例(密度)
        float density = getResources().getDisplayMetrics().density;
        return (int) (dip * density + 0.5);
    }