예제 #1
0
 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);
 }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.verify);
    ViewUtils.inject(this);
    // 记录Activity以便退出时全部finish()
    Const.activityList.add(this);

    count = new TimeCount(60000, 1000); // 构造CountDownTimer对象
    Button goButton = (Button) findViewById(R.id.gobutton);
    ImageView back = (ImageView) findViewById(R.id.ivAppBack);

    textState.setTextSize(12);
    SpannableStringBuilder spannableStringBuilder =
        new SpannableStringBuilder("点击“手机绑定登陆”,即表示同意《超速洗用户协议》");
    ForegroundColorSpan blueSpan = new ForegroundColorSpan(Color.parseColor("#28ccfc"));
    spannableStringBuilder.setSpan(
        new URLSpan("http://www.baidu.com"),
        16,
        spannableStringBuilder.length(),
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannableStringBuilder.setSpan(
        blueSpan, 16, spannableStringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    textState.setMovementMethod(LinkMovementMethod.getInstance());
    textState.setText(spannableStringBuilder);
  }
예제 #3
0
  public static void setNameAndUsername(TextView textView, String name, String username) {
    Context c = textView.getContext();

    ForegroundColorSpan grayTextForegroundSpan =
        new ForegroundColorSpan(c.getResources().getColor(R.color.name_gray));

    AbsoluteSizeSpan fontsizeSpan = new AbsoluteSizeSpan(20);

    SpannableStringBuilder ssb = new SpannableStringBuilder(name + " @" + username);

    // Apply the color span
    ssb.setSpan(
        grayTextForegroundSpan, // the span to add
        name.length() + 1, // the start of the span (inclusive)
        ssb.length(), // the end of the span (exclusive)
        Spanned
            .SPAN_EXCLUSIVE_EXCLUSIVE); // behavior when text is later inserted into the
                                        // SpannableStringBuilder

    ssb.setSpan(
        fontsizeSpan, // the span to add
        name.length() + 1, // the start of the span (inclusive)
        ssb.length(), // the end of the span (exclusive)
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    textView.setText(ssb);
  }
예제 #4
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));
      }
    }
예제 #5
0
  /**
   * Sets the styling for string with code segments.
   *
   * <p>The general process is to search for <code>[[&lt;[</code> and <code>]&gt;]]</code> tokens to
   * find the code fragments within the escaped text. A <code>Spannable</code> is created which
   * which breaks up the origin sequence into non-code and code fragments, and applies a monospace
   * font to the code fragments.
   *
   * @param sequence the Spannable generated from Html.fromHtml
   * @return the message with monospace font applied to code fragments
   */
  private CharSequence setCodeFont(SpannableStringBuilder sequence) {
    int start = 0;
    int end = 0;
    for (int i = 0; i < sequence.length(); i++) {
      if (sequence.charAt(i) == '[' && i < sequence.length() - 3) {
        if (sequence.charAt(i + 1) == '['
            && sequence.charAt(i + 2) == '<'
            && sequence.charAt(i + 3) == '[') {
          start = i;
        }
      } else if (sequence.charAt(i) == ']' && i < sequence.length() - 3) {
        if (sequence.charAt(i + 1) == '>'
            && sequence.charAt(i + 2) == ']'
            && sequence.charAt(i + 3) == ']') {
          end = i;
        }
      }

      if (end > start) {
        sequence.delete(end, end + 4);
        sequence.delete(start, start + 4);
        sequence.setSpan(
            new TypefaceSpan("monospace"), start, end - 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        start = 0;
        end = 0;
        i = i - 4; // move back to compensate for removal of [[<[
      }
    }

    return sequence;
  }
예제 #6
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);
 }
 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;
 }
예제 #8
0
  @WrapForJNI
  @Override
  public void onSelectionChange(final int start, final int end) {
    if (DEBUG) {
      // GeckoEditableListener methods should all be called from the Gecko thread
      ThreadUtils.assertOnGeckoThread();
      Log.d(LOGTAG, "onSelectionChange(" + start + ", " + end + ")");
    }
    if (start < 0 || start > mText.length() || end < 0 || end > mText.length()) {
      Log.e(
          LOGTAG,
          "invalid selection notification range: "
              + start
              + " to "
              + end
              + ", length: "
              + mText.length());
      throw new IllegalArgumentException("invalid selection notification range");
    }
    final int seqnoWhenPosted = ++mGeckoUpdateSeqno;

    /* An event (keypress, etc.) has potentially changed the selection,
    synchronize the selection here. There is not a race with the IC thread
    because the IC thread should be blocked on the event action */
    final Action action = mActionQueue.peek();
    if (action != null && action.mType == Action.TYPE_EVENT) {
      Selection.setSelection(mText, start, end);
      return;
    }

    geckoPostToIc(
        new Runnable() {
          @Override
          public void run() {
            mActionQueue.syncWithGecko();
            /* check to see there has not been another action that potentially changed the
            selection. If so, we can skip this update because we know there is another
            update right after this one that will replace the effect of this update */
            if (mGeckoUpdateSeqno == seqnoWhenPosted) {
              /* In this case, Gecko's selection has changed and it's notifying us to change
              Java's selection. In the normal case, whenever Java's selection changes,
              we go back and set Gecko's selection as well. However, in this case,
              since Gecko's selection is already up-to-date, we skip this step. */
              boolean oldUpdateGecko = mUpdateGecko;
              mUpdateGecko = false;
              Selection.setSelection(mProxy, start, end);
              mUpdateGecko = oldUpdateGecko;
            }
          }
        });
  }
예제 #9
0
  /**
   * Set the necessary spans for each spoiler.
   *
   * <p>The algorithm works in the same way as <code>setCodeFont</code>.
   *
   * @param sequence
   * @return
   */
  private CharSequence setSpoilerStyle(SpannableStringBuilder sequence) {
    int start = 0;
    int end = 0;
    for (int i = 0; i < sequence.length(); i++) {
      if (sequence.charAt(i) == '[' && i < sequence.length() - 3) {
        if (sequence.charAt(i + 1) == '['
            && sequence.charAt(i + 2) == 's'
            && sequence.charAt(i + 3) == '[') {
          start = i;
        }
      } else if (sequence.charAt(i) == ']' && i < sequence.length() - 3) {
        if (sequence.charAt(i + 1) == 's'
            && sequence.charAt(i + 2) == ']'
            && sequence.charAt(i + 3) == ']') {
          end = i;
        }
      }

      if (end > start) {
        sequence.delete(end, end + 4);
        sequence.delete(start, start + 4);
        BackgroundColorSpan backgroundColorSpan = new BackgroundColorSpan(Color.BLACK);
        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.BLACK);

        URLSpan urlSpan = sequence.getSpans(start, start, URLSpan.class)[0];
        sequence.setSpan(
            urlSpan, sequence.getSpanStart(urlSpan), start - 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);

        // spoiler text has a space at the front
        sequence.setSpan(
            backgroundColorSpan, start + 1, end - 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        sequence.setSpan(foregroundColorSpan, start, end - 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);

        storedSpoilerSpans.add(foregroundColorSpan);
        storedSpoilerSpans.add(backgroundColorSpan);
        // Shift 1 to account for remove of beginning "<"
        storedSpoilerStarts.add(start - 1);
        storedSpoilerStarts.add(start - 1);
        storedSpoilerEnds.add(end - 5);
        storedSpoilerEnds.add(end - 5);

        sequence.delete(start - 2, start - 1); // remove the trailing <
        start = 0;
        end = 0;
        i = i - 5; // move back to compensate for removal of [[s[
      }
    }

    return sequence;
  }
예제 #10
0
파일: cnp.java 프로젝트: ChiangC/FMTech
 public final void run() {
   if ((this.a.F) || (!this.a.i())) {
     return;
   }
   Spanned localSpanned = Html.fromHtml(this.a.az);
   if ((localSpanned instanceof SpannableStringBuilder)) {}
   int i;
   int j;
   for (SpannableStringBuilder localSpannableStringBuilder = (SpannableStringBuilder) localSpanned;
       ;
       localSpannableStringBuilder = new SpannableStringBuilder(localSpanned)) {
     i = localSpannableStringBuilder.length();
     for (j = 0;
         (j != i) && (Character.isWhitespace(localSpannableStringBuilder.charAt(j)));
         j++) {}
   }
   if (j != 0) {
     localSpannableStringBuilder.delete(0, j);
     i = localSpannableStringBuilder.length();
   }
   for (int k = i - 1;
       (k >= 0) && (Character.isWhitespace(localSpannableStringBuilder.charAt(k)));
       k--) {}
   if (k != i - 1) {
     localSpannableStringBuilder.delete(k + 1, i);
   }
   this.a.ax.setText(localSpannableStringBuilder);
   Linkify.addLinks(this.a.ax, 1);
   this.a.ax.setVisibility(0);
   this.a.ax.setMovementMethod(LinkMovementMethod.getInstance());
   this.a.ay.setVisibility(0);
 }
  private FixingResult addSpacesAroundSpansUntilFixed(
      SpannableStringBuilder builder, int widthMeasureSpec, int heightMeasureSpec) {

    Object[] spans = builder.getSpans(0, builder.length(), Object.class);
    List<Object> spansWithSpacesBefore = new ArrayList<Object>(spans.length);
    List<Object> spansWithSpacesAfter = new ArrayList<Object>(spans.length);

    for (Object span : spans) {
      int spanStart = builder.getSpanStart(span);
      if (isNotSpace(builder, spanStart - 1)) {
        builder.insert(spanStart, " ");
        spansWithSpacesBefore.add(span);
      }

      int spanEnd = builder.getSpanEnd(span);
      if (isNotSpace(builder, spanEnd)) {
        builder.insert(spanEnd, " ");
        spansWithSpacesAfter.add(span);
      }

      try {
        setTextAndMeasure(builder, widthMeasureSpec, heightMeasureSpec);
        return FixingResult.fixed(spansWithSpacesBefore, spansWithSpacesAfter);
      } catch (IndexOutOfBoundsException notFixed) {
      }
    }
    if (HtmlTextView.DEBUG) {
      Log.d(HtmlTextView.TAG, "Could not fix the Spanned by adding spaces around spans");
    }
    return FixingResult.notFixed();
  }
예제 #12
0
  private void notifyCommitComposition() {
    // Gecko already committed its composition, and
    // we should remove the composition on our side as well.
    boolean wasComposing = false;
    final Object[] spans = mText.getSpans(0, mText.length(), Object.class);

    for (Object span : spans) {
      if ((mText.getSpanFlags(span) & Spanned.SPAN_COMPOSING) != 0) {
        mText.removeSpan(span);
        wasComposing = true;
      }
    }

    if (!wasComposing) {
      return;
    }

    // Generate a text change notification if we actually cleared the composition.
    final CharSequence text = TextUtils.stringOrSpannedString(mText);
    geckoPostToIc(
        new Runnable() {
          @Override
          public void run() {
            mListener.onTextChange(text, 0, text.length(), text.length());
          }
        });
  }
예제 #13
0
  @Override
  public void onBindViewHolder(ViewHolder holder, int position) {
    Gank gank = mGankList.get(position);
    if (position == 0) {
      showCategory(holder);
    } else {
      boolean theCategoryOfLastEqualsToThis =
          mGankList.get(position - 1).type.equals(mGankList.get(position).type);
      if (!theCategoryOfLastEqualsToThis) {
        showCategory(holder);
      } else {
        hideCategory(holder);
      }
    }
    holder.category.setText(gank.type);
    SpannableStringBuilder builder =
        new SpannableStringBuilder(gank.desc)
            .append(
                StringStyles.format(
                    holder.gank.getContext(),
                    " (via. " + gank.who + ")",
                    R.style.ViaTextAppearance));
    CharSequence gankText = builder.subSequence(0, builder.length());

    holder.gank.setText(gankText);
    showItemAnim(holder.gank, position);
  }
  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;
  }
예제 #15
0
  /**
   * 组合消息文本
   *
   * @param name
   * @param body
   * @return
   */
  public static SpannableStringBuilder parseFriendPostpan(
      String name, SpannableStringBuilder body) {
    SpannableStringBuilder sp = null;
    int start = 0;
    int end = 0;
    String mName = name + ":";
    sp = body.insert(0, mName);
    // sp = new SpannableString(name + ":" + body);
    end = name.length();

    // 设置用户名字体加粗、高亮
    sp.setSpan(
        new StyleSpan(android.graphics.Typeface.BOLD),
        start,
        end,
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    sp.setSpan(
        new ForegroundColorSpan(Color.parseColor("#2f548f")),
        start,
        end,
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    sp.setSpan(
        new ForegroundColorSpan(Color.parseColor("#ff000000")),
        end,
        sp.length(),
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return sp;
  }
예제 #16
0
 /**
  * get real translate charsequence
  *
  * @param content
  * @return
  */
 public static CharSequence getTranslateTxt(CharSequence content) {
   StringBuilder sBuilder = new StringBuilder();
   if (content instanceof SpannableStringBuilder) {
     SpannableStringBuilder spanSb = (SpannableStringBuilder) content;
     if (spanSb.toString().contains(EMHolderEntity.FINAL_HOLDER)) {
       for (int i = 0; i < spanSb.length(); i++) {
         ReplacementSpan[] spans = spanSb.getSpans(i, i + 1, ReplacementSpan.class);
         if (spans.length > 0) {
           if (spans[0] instanceof EMImageSpan) {
             EMImageSpan imgSpan = (EMImageSpan) spans[0];
             sBuilder.append(imgSpan.mTransferTxt);
           } else if (spans[0] instanceof DefEmojSpan) {
             DefEmojSpan defSpan = (DefEmojSpan) spans[0];
             sBuilder.append(defSpan.mTransferTxt);
           }
         } else {
           sBuilder.append(spanSb.subSequence(i, i + 1));
         }
       }
     } else {
       sBuilder.append(content);
     }
   }
   return sBuilder;
 }
예제 #17
0
  /**
   * 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;
  }
예제 #18
0
  public void testFilter() {
    // Define the variables
    CharSequence source;
    SpannableStringBuilder dest;
    // Constructor to create a LengthFilter
    LengthFilter lengthFilter = new LengthFilter(10);
    InputFilter[] filters = {lengthFilter};

    // filter() implicitly invoked. If the total length > filter length, the filter will
    // cut off the source CharSequence from beginning to fit the filter length.
    source = "abc";
    dest = new SpannableStringBuilder("abcdefgh");
    dest.setFilters(filters);

    dest.insert(1, source);
    String expectedString1 = "aabbcdefgh";
    assertEquals(expectedString1, dest.toString());

    dest.replace(5, 8, source);
    String expectedString2 = "aabbcabcgh";
    assertEquals(expectedString2, dest.toString());

    dest.delete(1, 3);
    String expectedString3 = "abcabcgh";
    assertEquals(expectedString3, dest.toString());

    // filter() explicitly invoked
    dest = new SpannableStringBuilder("abcdefgh");
    CharSequence beforeFilterSource = "TestLengthFilter";
    String expectedAfterFilter = "TestLength";
    CharSequence actualAfterFilter =
        lengthFilter.filter(
            beforeFilterSource, 0, beforeFilterSource.length(), dest, 0, dest.length());
    assertEquals(expectedAfterFilter, actualAfterFilter);
  }
예제 #19
0
  public static void tryFlowText(
      SpannableStringBuilder ss, View thumbnailView, TextView messageView, Display display) {
    // There is nothing I can do for older versions, so just return
    if (!mNewClassAvailable) return;

    // Get height and width of the image and height of the text line
    thumbnailView.measure(display.getWidth(), display.getHeight());
    int height = thumbnailView.getMeasuredHeight();
    int width = thumbnailView.getMeasuredWidth();
    float textLineHeight = messageView.getPaint().getTextSize();

    // Set the span according to the number of lines and width of the image
    int lines = (int) Math.round(height / textLineHeight);
    // For an html text you can use this line: SpannableStringBuilder ss =
    // (SpannableStringBuilder)Html.fromHtml(text);
    ss.setSpan(new MyLeadingMarginSpan2(lines, width), 0, ss.length(), 0);
    messageView.setText(ss);

    // Align the text with the image by removing the rule that the text is
    // to the right of the image
    RelativeLayout.LayoutParams params =
        (RelativeLayout.LayoutParams) messageView.getLayoutParams();
    int[] rules = params.getRules();
    rules[RelativeLayout.RIGHT_OF] = 0;
  }
  @Override
  protected void replaceText(CharSequence text) {
    clearComposingText();
    SpannableStringBuilder ssb = buildSpannableForText(text);
    TokenImageSpan tokenSpan = buildSpanForObject(selectedObject);

    Editable editable = getText();
    int end = getSelectionEnd();
    int start = tokenizer.findTokenStart(editable, end);
    if (start < prefix.length()) {
      start = prefix.length();
    }
    String original = TextUtils.substring(editable, start, end);

    if (editable != null) {
      if (tokenSpan == null) {
        editable.replace(start, end, " ");
      } else if (!allowDuplicates && objects.contains(tokenSpan.getToken())) {
        editable.replace(start, end, " ");
      } else {
        QwertyKeyListener.markAsReplaced(editable, start, end, original);
        editable.replace(start, end, ssb);
        editable.setSpan(
            tokenSpan, start, start + ssb.length() - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
      }
    }
  }
예제 #21
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;
  }
예제 #22
0
  private void geckoActionReply() {
    if (DEBUG) {
      // GeckoEditableListener methods should all be called from the Gecko thread
      ThreadUtils.assertOnGeckoThread();
    }

    final Action action = mActionQueue.peek();
    if (action == null) {
      throw new IllegalStateException("empty actions queue");
    }

    if (DEBUG) {
      Log.d(LOGTAG, "reply: Action(" + getConstantName(Action.class, "TYPE_", action.mType) + ")");
    }
    switch (action.mType) {
      case Action.TYPE_SET_SELECTION:
        final int len = mText.length();
        final int curStart = Selection.getSelectionStart(mText);
        final int curEnd = Selection.getSelectionEnd(mText);
        // start == -1 when the start offset should remain the same
        // end == -1 when the end offset should remain the same
        final int selStart = Math.min(action.mStart < 0 ? curStart : action.mStart, len);
        final int selEnd = Math.min(action.mEnd < 0 ? curEnd : action.mEnd, len);

        if (selStart < action.mStart || selEnd < action.mEnd) {
          Log.w(LOGTAG, "IME sync error: selection out of bounds");
        }
        Selection.setSelection(mText, selStart, selEnd);
        geckoPostToIc(
            new Runnable() {
              @Override
              public void run() {
                mActionQueue.syncWithGecko();
                final int start = Selection.getSelectionStart(mText);
                final int end = Selection.getSelectionEnd(mText);
                if (selStart == start && selEnd == end) {
                  // There has not been another new selection in the mean time that
                  // made this notification out-of-date
                  mListener.onSelectionChange(start, end);
                }
              }
            });
        break;

      case Action.TYPE_SET_SPAN:
        mText.setSpan(action.mSpanObject, action.mStart, action.mEnd, action.mSpanFlags);
        break;

      case Action.TYPE_REMOVE_SPAN:
        mText.removeSpan(action.mSpanObject);
        break;

      case Action.TYPE_SET_HANDLER:
        geckoSetIcHandler(action.mHandler);
        break;
    }
    if (action.mShouldUpdate) {
      geckoUpdateGecko(false);
    }
  }
  private void updateTextDataUI() {

    if (!mIsTimestampDisplayMode) {
      if (mDataBufferLastSize != mDataBuffer.size()) {

        final int bufferSize = mDataBuffer.size();
        if (bufferSize > maxPacketsToPaintAsText) {
          mDataBufferLastSize = bufferSize - maxPacketsToPaintAsText;
          mTextSpanBuffer.clear();
          addTextToSpanBuffer(
              mTextSpanBuffer, getString(R.string.uart_text_dataomitted) + "\n", mInfoColor);
        }

        // Log.d(TAG, "update packets: "+(bufferSize-mDataBufferLastSize));
        for (int i = mDataBufferLastSize; i < bufferSize; i++) {
          final UartDataChunk dataChunk = mDataBuffer.get(i);
          final boolean isRX = dataChunk.getMode() == UartDataChunk.TRANSFERMODE_RX;
          final String data = dataChunk.getData();
          final String formattedData = mShowDataInHexFormat ? asciiToHex(data) : data;
          addTextToSpanBuffer(mTextSpanBuffer, formattedData, isRX ? mRxColor : mTxColor);
        }

        mDataBufferLastSize = mDataBuffer.size();
        mBufferTextView.setText(mTextSpanBuffer);
        mBufferTextView.setSelection(
            0, mTextSpanBuffer.length()); // to automatically scroll to the end
      }
    }
  }
예제 #24
0
 public MDFormatter(List<Markdown.MDLine> lines) {
   for (Markdown.MDLine line : lines) {
     format(line);
   }
   mBuilder.setSpan(
       new TypefaceSpan("monospace"), 0, mBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
 }
예제 #25
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);
 }
예제 #26
0
 private void clearCachedMark(SpannableStringBuilder ssb) {
   Cached[] cs = ssb.getSpans(0, ssb.length(), Cached.class);
   if (cs != null && cs.length > 0) {
     for (Cached c : cs) {
       ssb.removeSpan(c);
     }
   }
 }
예제 #27
0
  private void showNote(boolean xml) {

    if (xml) {
      content.setText(note.getXmlContent());
      title.setText((CharSequence) note.getTitle());
      this.setTitle(this.getTitle() + " - XML");
      return;
    }

    LinkInternalSpan[] links =
        noteContent.getSpans(0, noteContent.length(), LinkInternalSpan.class);
    MatchFilter noteLinkMatchFilter = LinkInternalSpan.getNoteLinkMatchFilter(noteContent, links);

    // show the note (spannable makes the TextView able to output styled text)
    content.setText(noteContent, TextView.BufferType.SPANNABLE);

    // add links to stuff that is understood by Android except phone numbers because it's too
    // aggressive
    // TODO this is SLOWWWW!!!!

    int linkFlags = 0;

    if (Preferences.getBoolean(Preferences.Key.LINK_EMAILS)) linkFlags |= Linkify.EMAIL_ADDRESSES;
    if (Preferences.getBoolean(Preferences.Key.LINK_URLS)) linkFlags |= Linkify.WEB_URLS;
    if (Preferences.getBoolean(Preferences.Key.LINK_ADDRESSES)) linkFlags |= Linkify.MAP_ADDRESSES;

    Linkify.addLinks(content, linkFlags);

    // Custom phone number linkifier (fixes lp:512204)
    if (Preferences.getBoolean(Preferences.Key.LINK_PHONES))
      Linkify.addLinks(
          content,
          LinkifyPhone.PHONE_PATTERN,
          "tel:",
          LinkifyPhone.sPhoneNumberMatchFilter,
          Linkify.sPhoneNumberTransformFilter);

    // This will create a link every time a note title is found in the text.
    // The pattern contains a very dumb (title1)|(title2) escaped correctly
    // Then we transform the url from the note name to the note id to avoid characters that mess up
    // with the URI (ex: ?)
    if (Preferences.getBoolean(Preferences.Key.LINK_TITLES)) {
      Pattern pattern = NoteManager.buildNoteLinkifyPattern(this, note.getTitle());

      if (pattern != null) {
        Linkify.addLinks(
            content,
            pattern,
            Tomdroid.CONTENT_URI + "/",
            noteLinkMatchFilter,
            noteTitleTransformFilter);

        // content.setMovementMethod(LinkMovementMethod.getInstance());
      }
    }
    title.setText((CharSequence) note.getTitle());
  }
예제 #28
0
 public void hidePost(String reason) {
   hidden = true;
   imagesLayout.setVisibility(View.GONE);
   SpannableStringBuilder builder =
       new SpannableStringBuilder("\nСообщение скрыто: " + reason + "\n");
   builder.setSpan(
       new ClickableSpan() {
         @Override
         public void onClick(View widget) {
           unhidePost();
         }
       },
       1,
       builder.length(),
       0);
   messageView.setText(builder.subSequence(0, builder.length()));
   return;
 }
  private CharSequence formatFrom(Recipients from, long count, boolean read) {
    String fromString = from.toShortString();
    SpannableStringBuilder builder = new SpannableStringBuilder(fromString);

    if (count > 0) {
      builder.append(" " + count);
      builder.setSpan(
          new ForegroundColorSpan(Color.parseColor("#66333333")),
          fromString.length(),
          builder.length(),
          Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    }

    if (!read) {
      builder.setSpan(
          new StyleSpan(Typeface.BOLD), 0, builder.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    }

    return builder;
  }
예제 #30
0
  public XImageSpan createAndPutChipForUser(TLRPC.User user) {
    LayoutInflater lf =
        (LayoutInflater)
            ApplicationLoader.applicationContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    View textView = lf.inflate(R.layout.group_create_bubble, null);
    TextView text = (TextView) textView.findViewById(R.id.bubble_text_view);
    String name = ContactsController.formatName(user.first_name, user.last_name);
    if (name.length() == 0 && user.phone != null && user.phone.length() != 0) {
      name = PhoneFormat.getInstance().format("+" + user.phone);
    }
    text.setText(name + ", ");

    int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    textView.measure(spec, spec);
    textView.layout(0, 0, textView.getMeasuredWidth(), textView.getMeasuredHeight());
    Bitmap b =
        Bitmap.createBitmap(textView.getWidth(), textView.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(b);
    canvas.translate(-textView.getScrollX(), -textView.getScrollY());
    textView.draw(canvas);
    textView.setDrawingCacheEnabled(true);
    Bitmap cacheBmp = textView.getDrawingCache();
    Bitmap viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true);
    textView.destroyDrawingCache();

    final BitmapDrawable bmpDrawable = new BitmapDrawable(b);
    bmpDrawable.setBounds(0, 0, b.getWidth(), b.getHeight());

    SpannableStringBuilder ssb = new SpannableStringBuilder("");
    XImageSpan span = new XImageSpan(bmpDrawable, ImageSpan.ALIGN_BASELINE);
    allSpans.add(span);
    selectedContacts.put(user.id, span);
    for (ImageSpan sp : allSpans) {
      ssb.append("<<");
      ssb.setSpan(
          sp, ssb.length() - 2, ssb.length(), SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    userSelectEditText.setText(ssb);
    userSelectEditText.setSelection(ssb.length());
    return span;
  }