示例#1
0
  Spannable diffSpannable(LinkedList<SyncTextDiff> diffs) {
    SpannableStringBuilder result = new SpannableStringBuilder();

    int start;
    String text;
    int color = Color.YELLOW;
    for (SyncTextDiff diff : diffs) {
      start = result.length();
      text = diff.text;
      switch (diff.operation) {
        case SyncTextDiff.DELETE:
          result.append(text, new BackgroundColorSpan(color), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
          result.setSpan(
              new StrikethroughSpan(),
              start,
              start + text.length(),
              Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
          break;
        case SyncTextDiff.INSERT:
          result.append(text, new BackgroundColorSpan(color), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
          break;
        case SyncTextDiff.EQUAL:
          result.append(text);
          break;
      }
    }
    return result;
  }
 public void updateText(@Nullable BidiFormatter formatter) {
   final SpannableStringBuilder sb = new SpannableStringBuilder();
   final String primaryText = mNameFirst ? mName : mScreenName;
   final String secondaryText = mNameFirst ? mScreenName : mName;
   if (primaryText != null) {
     int start = sb.length();
     if (formatter != null && !isInEditMode()) {
       sb.append(formatter.unicodeWrap(primaryText));
     } else {
       sb.append(primaryText);
     }
     int end = sb.length();
     sb.setSpan(mPrimaryTextColor, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
     sb.setSpan(mPrimaryTextStyle, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
     sb.setSpan(mPrimaryTextSize, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
   }
   sb.append(mTwoLine ? '\n' : ' ');
   if (secondaryText != null) {
     int start = sb.length();
     if (formatter != null && !isInEditMode()) {
       sb.append(formatter.unicodeWrap(secondaryText));
     } else {
       sb.append(secondaryText);
     }
     int end = sb.length();
     sb.setSpan(mSecondaryTextColor, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
     sb.setSpan(mSecondaryTextStyle, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
     sb.setSpan(mSecondaryTextSize, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
   }
   setText(sb);
 }
示例#3
0
 public void showAbout(View view) {
   final SpannableStringBuilder sb = new SpannableStringBuilder();
   final String appName = getResources().getString(R.string.app_name);
   sb.append(Html.fromHtml("<h1>" + appName + "</h1>"));
   sb.append(getResources().getString(R.string.version)).append('\n');
   sb.append(getResources().getString(R.string.copyright))
       .append(" (")
       .append(
           SpannedUtil.createAuthorsLink(
               "module-smssend", getResources().getString(R.string.authors)))
       .append(")\n");
   sb.append('\n');
   sb.append(appName).append(' ').append(getResources().getText(R.string.gplv3));
   final TextView textView = new TextView(this);
   textView.setText(sb);
   textView.setMovementMethod(LinkMovementMethod.getInstance());
   // Sadly we can't make this text view also selectable
   // http://stackoverflow.com/questions/14862750
   // @formatter:off
   final AlertDialog alertDialog =
       new AlertDialog.Builder(this)
           .setPositiveButton(getResources().getString(R.string.close), null)
           .setView(textView)
           .create();
   // @formatter:on
   alertDialog.show();
 }
  /**
   * Appends CharSequence representations of the specified arguments to a {@link
   * SpannableStringBuilder}, creating one if the supplied builder is {@code null}.
   *
   * @param builder An existing {@link SpannableStringBuilder}, or {@code null} to create one.
   * @param args The objects to append to the builder.
   * @return A builder with the specified objects appended.
   */
  public static SpannableStringBuilder appendWithSeparator(
      SpannableStringBuilder builder, CharSequence... args) {
    if (builder == null) {
      builder = new SpannableStringBuilder();
    }

    for (CharSequence arg : args) {
      if (arg == null) {
        continue;
      }

      if (arg.toString().length() == 0) {
        continue;
      }

      if (builder.length() > 0) {
        if (needsBreakingSeparator(builder)) {
          builder.append(DEFAULT_BREAKING_SEPARATOR);
        } else {
          builder.append(DEFAULT_SEPARATOR);
        }
      }

      builder.append(arg);
    }

    return builder;
  }
  private String getCustomValuesText(PDroidAppSetting setting) {
    if (setting.getCustomValues() != null && setting.getCustomValues().size() > 0) {
      List<String> customValueStrings = new LinkedList<String>();
      for (SimpleImmutableEntry<String, String> customValue : setting.getCustomValues()) {
        SpannableStringBuilder builder = new SpannableStringBuilder();
        if (customValue.getKey() != null && !(customValue.getKey().isEmpty())) {
          builder.append(customValue.getKey()).append(":");
        }
        if (customValue.getValue() != null && !(customValue.getValue().isEmpty())) {
          builder.append(customValue.getValue());
          builder.setSpan(
              new StyleSpan(Typeface.ITALIC),
              builder.length() - customValue.getValue().length(),
              builder.length(),
              0);
        }

        if (!builder.toString().isEmpty()) {
          customValueStrings.add(builder.toString());
        }
      }

      if (customValueStrings.size() > 0) {
        return TextUtils.join(
            context.getString(R.string.detail_custom_value_spacer), customValueStrings);
      }
    }
    return null;
  }
  private void appendLog(String message, String targetFragment) {
    log.append(message);

    if (EXPECTED_TARGET_FRAGMENT.equals(targetFragment)) {
      SpannableString span = new SpannableString(targetFragment);
      span.setSpan(
          new ForegroundColorSpan(COLOR_OK),
          0,
          targetFragment.length(),
          Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
      log.append(span);
    } else {
      SpannableString span = new SpannableString(targetFragment);
      span.setSpan(
          new ForegroundColorSpan(COLOR_NOK),
          0,
          targetFragment.length(),
          Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
      log.append(span);
    }
    log.append("\n\n");

    if (logView != null) {
      logView.setText(log);
    }
  }
    protected void onPostExecute(JSONObject result) {
      if (statusFieldPosition == 0) {
        statusFieldPosition = statusField.getTop();
      }

      if (result != null) {
        try {
          boolean status = result.getBoolean("status");

          SpannableStringBuilder stringBuilder =
              new SpannableStringBuilder(getText(R.string.power));
          if (status) {
            stringBuilder.append(" PÅ");
          } else {
            stringBuilder.append(" AV");
          }

          statusText.setText(stringBuilder, TextView.BufferType.SPANNABLE);
          statusField.animate().y(statusFieldPosition).setDuration(1000);

          String last_start = result.getString("last_start");
          SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
          SimpleDateFormat out = new SimpleDateFormat("hh:mm");
          Date last = df.parse(last_start);
          footerText.setText(getText(R.string.details) + " " + out.format(last));
        } catch (JSONException e) {
        } catch (ParseException e) {
        }
      } else {
        footerText.setText(getText(R.string.defaultFooterText));
      }
    }
示例#8
0
  private CharSequence formatMessage(MultiDeleteListItemData ch) {
    final int size = android.R.style.TextAppearance_Small;
    final int color = android.R.styleable.Theme_textColorSecondary;
    String from = ch.getFrom();

    SpannableStringBuilder buf = new SpannableStringBuilder(from);
    if (ch.hasDraft() && ch.getMessageCount() == 0) {
      // only draft
    } else {
      if (ch.getUnreadMessageCount() > 0) {
        buf.append(" (" + ch.getUnreadMessageCount() + "/");
      } else {
        buf.append(" (" + "0/");
      }
      // if (ch.getMessageCount() > 1) {
      buf.append(ch.getMessageCount() + ") ");
      // }
    }
    /*
    if (ch.getMessageCount() > 1) {
        buf.append(" (" + ch.getMessageCount() + ") ");
    }
    */
    return buf;
  }
 protected void setupView() {
   this.rootView = this.res.inflate(getContext(), R.layout.create_order_delivery, null, false);
   this.deliveryLayer = this.rootView.findViewById(R.id.delivery_info_layout);
   this.memoEt = ((EditText) this.rootView.findViewById(R.id.say_something));
   this.memoEt.addTextChangedListener(this.textWatcher);
   this.addressView = ((BasicSingleItem) this.rootView.findViewById(R.id.address));
   this.addressView.setOnClickListener(this);
   SpannableString localSpannableString = new SpannableString("请输入收货人");
   localSpannableString.setSpan(
       new AbsoluteSizeSpan(getResources().getDimensionPixelSize(R.dimen.text_size_17)),
       0,
       localSpannableString.length(),
       33);
   localSpannableString.setSpan(
       new ForegroundColorSpan(getResources().getColor(R.color.text_color_gray)),
       0,
       localSpannableString.length(),
       33);
   Object localObject = new SpannableString("请输入收货地址");
   ((SpannableString) localObject)
       .setSpan(
           new AbsoluteSizeSpan(getResources().getDimensionPixelSize(R.dimen.text_size_17)),
           0,
           ((SpannableString) localObject).length(),
           33);
   ((SpannableString) localObject)
       .setSpan(
           new ForegroundColorSpan(getResources().getColor(R.color.text_color_gray)),
           0,
           ((SpannableString) localObject).length(),
           33);
   SpannableStringBuilder localSpannableStringBuilder = new SpannableStringBuilder();
   localSpannableStringBuilder
       .append(localSpannableString)
       .append("\n")
       .append((CharSequence) localObject);
   this.addressView.setTitle(localSpannableStringBuilder);
   this.deliveryTypeItemView = ((BasicSingleItem) this.rootView.findViewById(R.id.delivery));
   this.deliveryTypeItemView.setOnClickListener(this);
   localSpannableString = new SpannableString("请选择收货方式");
   localSpannableString.setSpan(
       new AbsoluteSizeSpan(getResources().getDimensionPixelSize(R.dimen.text_size_17)),
       0,
       localSpannableString.length(),
       33);
   localSpannableString.setSpan(
       new ForegroundColorSpan(getResources().getColor(R.color.text_color_gray)),
       0,
       localSpannableString.length(),
       33);
   localObject = new SpannableStringBuilder();
   ((SpannableStringBuilder) localObject).append(localSpannableString);
   this.deliveryTypeItemView.setTitle((CharSequence) localObject);
   this.deliveryLayer.setVisibility(8);
 }
示例#10
0
 @Override
 public void bindView(final View view, final int position, final ViewGroup parent) {
   final DevotionActivity.DevotionKind kind = getItem(position);
   final SpannableStringBuilder sb = new SpannableStringBuilder();
   sb.append(kind.title);
   sb.append("\n");
   final int sb_len = sb.length();
   sb.append(kind.subtitle);
   sb.setSpan(new RelativeSizeSpan(0.7f), sb_len, sb.length(), 0);
   ((TextView) view).setText(sb);
 }
 @Override
 public CharSequence calculateValue(Object... args) throws Exception {
   int len = args.length;
   SpannableStringBuilder result = new SpannableStringBuilder("");
   for (int i = 0; i < len; i++) {
     if (args[i] == null) continue;
     if (args[i] instanceof CharSequence) result.append((CharSequence) args[i]);
     else result.append(args[i].toString());
   }
   return result.toString();
 }
 public Spannable formatField(String label, String value, int color1, int color2) {
   int start = 0;
   SpannableStringBuilder str = new SpannableStringBuilder(label == null ? "" : label);
   str.append(": ");
   int end = str.length();
   str.setSpan(new ForegroundColorSpan(color1), start, end, 0);
   start = end;
   str.append(value == null ? "" : value);
   end = str.length();
   str.setSpan(new ForegroundColorSpan(color2), start, end, 0);
   return str;
 }
  private void onQueryCfComplete(AsyncResult ar) {
    StringBuilder sb = new StringBuilder(getScString());
    sb.append("\n");

    if (ar.exception != null) {
      state = State.FAILED;
      sb.append(getErrorMessage(ar));
    } else {
      CallForwardInfo infos[];

      infos = (CallForwardInfo[]) ar.result;

      if (infos.length == 0) {
        // Assume the default is not active
        sb.append(context.getText(com.android.internal.R.string.serviceDisabled));

        // Set unconditional CFF in SIM to false
        if (phone.mSIMRecords != null) {
          phone.setCallForwardingPreference(false);
          phone.mSIMRecords.setVoiceCallForwardingFlag(1, false);
        } else {
          Log.w(LOG_TAG, "setVoiceCallForwardingFlag aborted. sim records is null.");
        }
      } else {

        SpannableStringBuilder tb = new SpannableStringBuilder();

        // Each bit in the service class gets its own result line
        // The service classes may be split up over multiple
        // CallForwardInfos. So, for each service class, find out
        // which CallForwardInfo represents it and then build
        // the response text based on that

        for (int serviceClassMask = 1;
            serviceClassMask <= SERVICE_CLASS_MAX;
            serviceClassMask <<= 1) {
          for (int i = 0, s = infos.length; i < s; i++) {
            if ((serviceClassMask & infos[i].serviceClass) != 0) {
              tb.append(makeCFQueryResultMessage(infos[i], serviceClassMask));
              tb.append("\n");
            }
          }
        }
        sb.append(tb);
      }

      state = State.COMPLETE;
    }

    message = sb;
    phone.onMMIDone(this);
  }
  private void addTextToSpanBuffer(SpannableStringBuilder spanBuffer, String text, int color) {

    if (kUseColorsForData) {
      final int from = spanBuffer.length();
      spanBuffer.append(text);
      spanBuffer.setSpan(
          new ForegroundColorSpan(color),
          from,
          from + text.length(),
          Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    } else {
      spanBuffer.append(text);
    }
  }
示例#15
0
  public static SpannableStringBuilder generateMultiColoredString(GCSavedSet savedSet) {
    SpannableStringBuilder builder = new SpannableStringBuilder();

    String shortenedColorString = convertColorListToShortenedColorString(savedSet.getColors());

    List<String> stringParts = getParts(shortenedColorString, 3);
    int index = 0;
    for (String colorAbbrev : stringParts) {
      String colorString = colorAbbrev.substring(0, 2);
      String powerString = colorAbbrev.substring(2, 3);
      GCColor color = GCColorUtil.getColorUsingAbbrev(colorString);
      GCPowerLevel powerLevel = GCPowerLevelUtil.getPowerLevelUsingAbbrev(powerString);
      int[] rgbValues;
      if (color.getTitle().equalsIgnoreCase(GCConstants.COLOR_CUSTOM)) {
        rgbValues = convertRgbToPowerLevel(savedSet.getCustomColors().get(index), powerLevel);
      } else {
        rgbValues = convertRgbToPowerLevel(color.getRGBValues(), powerLevel);
      }

      if (colorString.equalsIgnoreCase("--")) {
        SpannableString spannableString = new SpannableString(colorString);
        spannableString.setSpan(
            new ForegroundColorSpan(Color.argb(255, 255, 255, 255)), 0, colorString.length(), 0);
        builder.append(spannableString);
      } else {
        SpannableString spannableString = new SpannableString(colorAbbrev);
        spannableString.setSpan(
            new ForegroundColorSpan(Color.argb(255, rgbValues[0], rgbValues[1], rgbValues[2])),
            0,
            3,
            0);
        spannableString.setSpan(
            new SuperscriptSpan(),
            colorAbbrev.length() - 1,
            colorAbbrev.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(
            new RelativeSizeSpan(0.75f),
            colorAbbrev.length() - 1,
            colorAbbrev.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        builder.append(spannableString);
      }
      index++;
    }

    return builder;
  }
示例#16
0
 /** 设置颜色 */
 public void setResultColor(String checkName, String name, TextView result) {
   SpannableStringBuilder builder = new SpannableStringBuilder();
   int start = name.indexOf(checkName);
   int max = name.length();
   endMax = restrictMax;
   for (int i = 0; i < restrictMax; i++) { // 循环遍历字符串
     if (Pattern.compile("(?i)[a-z]").matcher(name).find()
         || Pattern.compile("(?i)[A-Z]").matcher(name).find()) { // 用char包装类中的判断数字的方法判断每一个字符
       endMax++;
     }
   }
   if (max > endMax) {
     name = name.substring(0, endMax);
     for (int i = 0; i < max - endMax; i++) {
       name += ".";
     }
   }
   builder.append(name);
   if (!checkName.equals("")) {
     builder.setSpan(
         new ForegroundColorSpan(Color.RED),
         start,
         start + checkName.length(),
         Spanned.SPAN_COMPOSING);
   }
   result.setText(builder, BufferType.EDITABLE);
 }
示例#17
0
  /**
   * Perform the conversion from Markdown to HTML.
   *
   * @param txt - input in markdown format
   * @return HTML block corresponding to txt passed in.
   */
  @Deprecated
  public SpannableStringBuilder markdown(
      String txt, SpannableStringBuilder ssb, ArrayList<MarkdownURL> urls) {
    if (txt == null) {
      txt = "";
    }

    // Standardize line endings:
    txt.replaceAll("\\r\\n", "\n"); // DOS to Unix
    txt.replaceAll("\\r", "\n"); // Mac to Unix
    txt.replaceAll("^[ \\t]+$", "");

    //        // Make sure $text ends with a couple of newlines:
    //        text.append("\n\n");

    //        text.detabify();
    txt.replaceAll("^[ ]+$", "");

    ssb.append(txt);
    // doAnchors originally called from runBlockGamut -> formParagraphs -> runSpanGamut
    urls.clear();
    doAnchors(ssb, urls);
    doAutoLinks(ssb, urls);

    //	        hashHTMLBlocks(text);
    //	        stripLinkDefinitions(text);
    //	        text = runBlockGamut(text);
    //	        unEscapeSpecialChars(text);

    //	        text.append("\n");

    Collections.sort(urls);
    return ssb;
  }
示例#18
0
    @Override
    public void handleTagNode(TagNode node, SpannableStringBuilder builder, int start, int end) {
      String src = node.getAttributeByName("src");

      if (src == null) {
        src = node.getAttributeByName("href");
      }

      if (src == null) {
        src = node.getAttributeByName("xlink:href");
      }
      builder.append("\uFFFC");

      String resolvedHref = spine.resolveHref(src);

      if (imageCache.containsKey(resolvedHref) && !fakeImages) {
        Drawable drawable = imageCache.get(resolvedHref);
        setImageSpan(builder, drawable, start, builder.length());
        LOG.debug("Got cached href: " + resolvedHref);
      } else {
        LOG.debug("Loading href: " + resolvedHref);
        loader.registerCallback(
            resolvedHref,
            new ImageCallback(resolvedHref, builder, start, builder.length(), fakeImages));
      }
    }
示例#19
0
 private void updateErrorText() {
   mErrorText.clear();
   mErrorText.clearSpans();
   final int length = mTextInputLayout.getEditText().length();
   if (length > 0) {
     mErrorText.append(String.valueOf(length));
     mErrorText.append(" / ");
     mErrorText.append(String.valueOf(mMaxLen));
     mErrorText.setSpan(
         mAlignmentSpan, 0, mErrorText.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
     if (hasValidLength()) {
       mErrorText.setSpan(
           mNormalTextAppearance, 0, mErrorText.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
     }
   }
   mTextInputLayout.setError(mErrorText);
 }
 private void setFace(SpannableStringBuilder spb, String smileName, int length) {
   String path = SmileTable.get(smileName);
   try {
     int height = (int) editTextFastReply.getTextSize() * 2;
     GifDrawable drawable = new GifDrawable(ChhApplication.getInstance().getAssets(), path);
     // Drawable drawable = Drawable.createFromStream(getResources().getAssets().open(path),
     // smileName);
     drawable.setBounds(0, 0, height, height);
     ImageSpan imageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
     SpannableString spanStr = new SpannableString(smileName);
     spanStr.setSpan(imageSpan, 0, length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
     spb.append(spanStr);
   } catch (IOException e) {
     e.printStackTrace();
     spb.append(smileName);
   }
 }
示例#21
0
 /**
  * Set up the additional headers text view with the supplied header data.
  *
  * @param additionalHeaders List of header entries. Each entry consists of a header name and a
  *     header value. Header names may appear multiple times.
  *     <p>This method is always called from within the UI thread by {@link
  *     #showAdditionalHeaders()}.
  */
 private void populateAdditionalHeadersView(final List<HeaderEntry> additionalHeaders) {
   SpannableStringBuilder sb = new SpannableStringBuilder();
   boolean first = true;
   for (HeaderEntry additionalHeader : additionalHeaders) {
     if (!first) {
       sb.append("\n");
     } else {
       first = false;
     }
     StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
     SpannableString label = new SpannableString(additionalHeader.label + ": ");
     label.setSpan(boldSpan, 0, label.length(), 0);
     sb.append(label);
     sb.append(MimeUtility.unfoldAndDecode(additionalHeader.value));
   }
   mAdditionalHeadersView.setText(sb);
 }
 @Override
 public void doAction(int paramInt, String paramString) {
   // TODO Auto-generated method stub
   EditText localEditBlogView = mEditAnswer;
   int i = localEditBlogView.getSelectionStart();
   int j = localEditBlogView.getSelectionStart();
   String str1 = "[" + paramString + "]";
   String str2 = localEditBlogView.getText().toString();
   SpannableStringBuilder localSpannableStringBuilder = new SpannableStringBuilder();
   localSpannableStringBuilder.append(str2, 0, i);
   localSpannableStringBuilder.append(str1);
   localSpannableStringBuilder.append(str2, j, str2.length());
   SociaxUIUtils.highlightContent(QuestionDetailsActivity.this, localSpannableStringBuilder);
   localEditBlogView.setText(localSpannableStringBuilder, TextView.BufferType.SPANNABLE);
   localEditBlogView.setSelection(i + str1.length());
   Log.v("Tag", localEditBlogView.getText().toString());
 }
示例#23
0
  /** 显示在输入框的注码 */
  public void showEditText() {
    SpannableStringBuilder builder = new SpannableStringBuilder();
    String zhumas = "";
    int num = 0; // 高亮小球数
    int length = 0;
    for (int j = 0; j < itemViewArray.get(0).areaNums.length; j++) {
      BallTable ballTable = itemViewArray.get(0).areaNums[j].table;
      int[] zhuMa = ballTable.getHighlightBallNOs();
      if (j != 0) {
        if (iCurrentButton == PublicConst.BUY_PL3_ZU3_DAN) {
          zhumas += ",";
        } else {
          zhumas += " | ";
        }
      }
      for (int i = 0; i < ballTable.getHighlightBallNOs().length; i++) {
        if (isTen) {
          zhumas += PublicMethod.getZhuMa(zhuMa[i]);
        } else {
          zhumas += zhuMa[i] + "";
        }

        if (i != ballTable.getHighlightBallNOs().length - 1) {
          zhumas += ",";
        }
      }
      num += zhuMa.length;
    }
    if (num == 0) {
      editZhuma.setText("");
    } else {
      builder.append(zhumas);
      String zhuma[];
      if (iCurrentButton == PublicConst.BUY_PL3_ZU3_DAN) {
        zhuma = zhumas.split("\\,");
      } else {
        zhuma = zhumas.split("\\|");
      }
      for (int i = 0; i < zhuma.length; i++) {
        if (i != 0) {
          length += zhuma[i].length() + 1;
        } else {
          length += zhuma[i].length();
        }
        if (i != zhuma.length - 1) {
          builder.setSpan(
              new ForegroundColorSpan(Color.BLACK), length, length + 1, Spanned.SPAN_COMPOSING);
        }
        builder.setSpan(
            new ForegroundColorSpan(itemViewArray.get(0).areaNums[i].textColor),
            length - zhuma[i].length(),
            length,
            Spanned.SPAN_COMPOSING);
      }
      editZhuma.setText(builder, BufferType.EDITABLE);
    }
  }
  public static CharSequence generateSearchName(String name, String name2, String q) {
    if (name == null && name2 == null) {
      return "";
    }
    SpannableStringBuilder builder = new SpannableStringBuilder();
    String wholeString = name;
    if (wholeString == null || wholeString.length() == 0) {
      wholeString = name2;
    } else if (name2 != null && name2.length() != 0) {
      wholeString += " " + name2;
    }
    wholeString = wholeString.trim();
    String lower = " " + wholeString.toLowerCase();
    String hexDarkColor =
        String.format("#%06X", (0xFFFFFF & AndroidUtilities.getIntDarkerColor("themeColor", 0x15)));
    int index = -1;
    int lastIndex = 0;
    while ((index = lower.indexOf(" " + q, lastIndex)) != -1) {
      int idx = index - (index == 0 ? 0 : 1);
      int end = q.length() + (index == 0 ? 0 : 1) + idx;

      if (lastIndex != 0 && lastIndex != idx + 1) {
        builder.append(wholeString.substring(lastIndex, idx));
      } else if (lastIndex == 0 && idx != 0) {
        builder.append(wholeString.substring(0, idx));
      }

      String query = wholeString.substring(idx, end);
      if (query.startsWith(" ")) {
        builder.append(" ");
      }
      query.trim();
      builder.append(Html.fromHtml("<font color=" + hexDarkColor + ">" + query + "</font>"));
      // builder.append(Html.fromHtml("<font color=\"#4d83b3\">" + query + "</font>"));

      lastIndex = end;
    }

    if (lastIndex != -1 && lastIndex != wholeString.length()) {
      builder.append(wholeString.substring(lastIndex, wholeString.length()));
    }

    return builder;
  }
示例#25
0
  private CharSequence formatMessage(
      MessageItem msgItem,
      String contact,
      String body,
      String subject,
      Pattern highlight,
      String contentType) {
    SpannableStringBuilder buf = new SpannableStringBuilder();

    boolean hasSubject = !TextUtils.isEmpty(subject);
    SmileyParser parser = SmileyParser.getInstance();
    if (hasSubject) {
      CharSequence smilizedSubject = parser.addSmileySpans(subject);
      // Can't use the normal getString() with extra arguments for string replacement
      // because it doesn't preserve the SpannableText returned by addSmileySpans.
      // We have to manually replace the %s with our text.
      buf.append(
          TextUtils.replace(
              mContext.getResources().getString(R.string.inline_subject),
              new String[] {"%s"},
              new CharSequence[] {smilizedSubject}));
    }

    if (!TextUtils.isEmpty(body)) {
      // Converts html to spannable if ContentType is "text/html".
      if (contentType != null && ContentType.TEXT_HTML.equals(contentType)) {
        buf.append("\n");
        buf.append(Html.fromHtml(body));
      } else {
        if (hasSubject) {
          buf.append(" - ");
        }
        buf.append(parser.addSmileySpans(body));
      }
    }

    if (highlight != null) {
      Matcher m = highlight.matcher(buf.toString());
      while (m.find()) {
        buf.setSpan(new StyleSpan(Typeface.BOLD), m.start(), m.end(), 0);
      }
    }
    return buf;
  }
  private SpannableString parseString(String inputStr) {
    SpannableStringBuilder spb = new SpannableStringBuilder();
    Pattern mPattern = Pattern.compile("\\[{1}.{2}\\]{1}");
    Matcher mMatcher = mPattern.matcher(inputStr);
    String tempStr = inputStr;

    while (mMatcher.find()) {
      int start = mMatcher.start();
      int end = mMatcher.end();
      spb.append(tempStr.substring(0, start));
      String faceName = mMatcher.group();
      setFace(spb, faceName, end - start);
      tempStr = tempStr.substring(end, tempStr.length());
      /** 更新查找的字符串 */
      mMatcher.reset(tempStr);
    }
    spb.append(tempStr);
    return new SpannableString(spb);
  }
示例#27
0
  /** 设置颜色 */
  public void setResultColor(String state, String resultStr, TextView result) {
    SpannableStringBuilder builder = new SpannableStringBuilder();

    resultStr = "(" + resultStr + ")";
    builder.append(resultStr);
    builder.setSpan(
        new ForegroundColorSpan(setColor(state)),
        1,
        resultStr.length() - 1,
        Spanned.SPAN_COMPOSING);
    result.setText(builder, BufferType.EDITABLE);
  }
示例#28
0
文件: TagUtil.java 项目: AxellH/docs
  /**
   * Create a colored spannable from tags.
   *
   * @param tags Tags
   * @return Colored spannable
   */
  public static Spannable buildSpannable(JSONArray tags) {
    SpannableStringBuilder builder = new SpannableStringBuilder();

    for (int i = 0; i < tags.length(); i++) {
      JSONObject tag = tags.optJSONObject(i);
      int start = builder.length();
      builder.append(" ").append(tag.optString("name")).append(" ");
      builder.setSpan(
          new ForegroundColorSpan(Color.WHITE),
          start,
          builder.length(),
          Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
      builder.setSpan(
          new BackgroundColorSpan(Color.parseColor(tag.optString("color"))),
          start,
          builder.length(),
          Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
      builder.append(" ");
    }

    return builder;
  }
示例#29
0
 public void setText(String text) {
   if (text == null || text.length() == 0) {
     setVisibility(GONE);
     return;
   }
   if (text != null && oldText != null && text.equals(oldText)) {
     return;
   }
   oldText = text;
   setVisibility(VISIBLE);
   if (AndroidUtilities.isTablet()) {
     width = (int) (AndroidUtilities.getMinTabletSide() * 0.7f);
   } else {
     width =
         (int) (Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) * 0.7f);
   }
   SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
   String help = LocaleController.getString("BotInfoTitle", R.string.BotInfoTitle);
   stringBuilder.append(help);
   stringBuilder.append("\n\n");
   stringBuilder.append(text);
   MessageObject.addLinks(stringBuilder);
   stringBuilder.setSpan(
       new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")),
       0,
       help.length(),
       Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
   textLayout =
       new StaticLayout(
           stringBuilder, textPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
   width = 0;
   height = textLayout.getHeight() + AndroidUtilities.dp(4 + 18);
   int count = textLayout.getLineCount();
   for (int a = 0; a < count; a++) {
     width =
         (int) Math.ceil(Math.max(width, textLayout.getLineWidth(a) - textLayout.getLineLeft(a)));
   }
   width += AndroidUtilities.dp(4 + 18);
 }
  private void refreshStatusView(
      String url,
      Map<String, String> requestHeaders,
      NetworkResponse networkResponse,
      String responseString,
      String errorMsg,
      VolleyError error) {
    String dateString;
    if (currencyPairsMapHelper != null && currencyPairsMapHelper.getDate() > 0)
      dateString =
          FormatUtilsBase.formatSameDayTimeOrDate(getContext(), currencyPairsMapHelper.getDate());
    else
      dateString =
          getContext()
              .getString(R.string.checker_add_dynamic_currency_pairs_dialog_last_sync_never);

    statusView.setText(
        getContext()
            .getString(R.string.checker_add_dynamic_currency_pairs_dialog_last_sync, dateString));
    if (currencyPairsMapHelper != null && currencyPairsMapHelper.getPairsCount() > 0)
      statusView.append(
          "\n"
              + getContext()
                  .getString(
                      R.string.checker_add_dynamic_currency_pairs_dialog_pairs,
                      currencyPairsMapHelper.getPairsCount()));

    SpannableStringBuilder ssb = new SpannableStringBuilder();

    if (errorMsg != null) {
      ssb.append("\n");
      ssb.append(getContext().getString(R.string.check_error_generic_prefix, errorMsg));
    }

    CheckErrorsUtils.formatResponseDebug(
        getContext(), ssb, url, requestHeaders, networkResponse, responseString, error);
    errorView.setText(ssb);
  }