Java Code Examples for android.text.Editable#charAt()

The following examples show how to use android.text.Editable#charAt() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConversationFragment.java    From Conversations with GNU General Public License v3.0 6 votes vote down vote up
private void highlightInConference(String nick) {
    final Editable editable = this.binding.textinput.getText();
    String oldString = editable.toString().trim();
    final int pos = this.binding.textinput.getSelectionStart();
    if (oldString.isEmpty() || pos == 0) {
        editable.insert(0, nick + ": ");
    } else {
        final char before = editable.charAt(pos - 1);
        final char after = editable.length() > pos ? editable.charAt(pos) : '\0';
        if (before == '\n') {
            editable.insert(pos, nick + ": ");
        } else {
            if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) {
                if (NickValidityChecker.check(conversation, Arrays.asList(editable.subSequence(0, pos - 2).toString().split(", ")))) {
                    editable.insert(pos - 2, ", " + nick);
                    return;
                }
            }
            editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " "));
            if (Character.isWhitespace(after)) {
                this.binding.textinput.setSelection(this.binding.textinput.getSelectionStart() + 1);
            }
        }
    }
}
 
Example 2
Source File: BracketHighlighter.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
public void onSelectChange(int selStart, int selEnd) {
    try {
        if (selEnd > -1 && selEnd < editText.length()) {
            Editable text = editText.getText();
            char chatAtCursor = text.charAt(selEnd);
            boolean bracket = isBracket(chatAtCursor);
            if (bracket && isOpen(chatAtCursor)) { //open
                findClose(chatAtCursor, selEnd);
            } else if (bracket) { //close
                findOpen(chatAtCursor, selEnd);
            } else {
                char before = selEnd > 0 ? text.charAt(selEnd - 1) : 0;
                bracket = isBracket(before);
                if (bracket && isOpen(before)) { //open
                    findClose(before, selEnd - 1);
                } else if (bracket) {
                    findOpen(before, selEnd - 1);
                }
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 3
Source File: AutoMultilineTextListener.java    From revolution-irc with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void afterTextChanged(Editable s) {
    if (mPossiblyNotMultiline) {
        boolean found = false;
        for (int i = s.length() - 1; i >= 0; --i) {
            if (s.charAt(i) == '\n') {
                found = true;
                break;
            }
        }
        if (!found) {
            mMultiline = false;
            updateMultilineStatus();
        }
    }
}
 
Example 4
Source File: AutohideFragment.java    From Dashchan with Apache License 2.0 6 votes vote down vote up
@Override
public void afterTextChanged(Editable s) {
	// Remove line breaks
	for (int i = 0; i < s.length(); i++) {
		char c = s.charAt(i);
		// Replacing or deleting will call this callback again
		if (c == '\n') {
			s.replace(i, i + 1, " ");
			return;
		} else if (c == '\r') {
			s.delete(i, i + 1);
			return;
		}
	}
	Pattern pattern = null;
	try {
		pattern = AutohideStorage.AutohideItem.makePattern(s.toString());
		updateError(-1, null);
	} catch (PatternSyntaxException e) {
		updateError(e.getIndex(), e.getDescription());
	}
	workPattern = pattern;
	updateTestResult();
}
 
Example 5
Source File: RecipientEditTextView.java    From talk-android with MIT License 6 votes vote down vote up
private int putOffsetInRange(int o) {
    int offset = o;
    Editable text = getText();
    int length = text.length();
    // Remove whitespace from end to find "real end"
    int realLength = length;
    for (int i = length - 1; i >= 0; i--) {
        if (text.charAt(i) == ' ') {
            realLength--;
        } else {
            break;
        }
    }

    // If the offset is beyond or at the end of the text,
    // leave it alone.
    if (offset >= realLength) {
        return offset;
    }
    Editable editable = getText();
    while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) {
        // Keep walking backward!
        offset--;
    }
    return offset;
}
 
Example 6
Source File: EditMessage.java    From Pix-Art-Messenger with GNU General Public License v3.0 6 votes vote down vote up
public void insertAsQuote(String text) {
    text = text.replaceAll("(\n *){2,}", "\n").replaceAll("(^|\n)", "$1> ").replaceAll("\n$", "");
    Editable editable = getEditableText();
    int position = getSelectionEnd();
    if (position == -1) position = editable.length();
    if (position > 0 && editable.charAt(position - 1) != '\n') {
        editable.insert(position++, "\n");
    }
    editable.insert(position, text);
    position += text.length();
    editable.insert(position++, "\n");
    if (position < editable.length() && editable.charAt(position) != '\n') {
        editable.insert(position, "\n");
    }
    setSelection(position);
}
 
Example 7
Source File: TextSpectator.java    From HgLauncher with GNU General Public License v3.0 5 votes vote down vote up
@Override public void afterTextChanged(Editable s) {
    if (!spaceSpam && s.length() > 0 && s.charAt(0) == ' ') {
        s.delete(0, 1);
    }

    afterChanged(s);
}
 
Example 8
Source File: AutoSplitTextHelper.java    From ViewPrinter with Apache License 2.0 5 votes vote down vote up
@Override
public void afterTextChanged(Editable s) {
    if (isActionInProgress()) return;
    setActionInProgress(true);
    boolean hasHiddenNewLine = s.length() > 0 && s.charAt(0) == NEWLINE;
    if (mHasHiddenNewline && !hasHiddenNewLine && !isFirst()) {
        // An hidden newline was removed! Pass stuff back.
        // This might make us empty, and eventually, delete us.
        LOG.w(logPrefix(), "afterTextChanged:",
                "we had a hidden newline, but not anymore.",
                "Passing \"isFirst line\" back.");
        previous().acceptSpace(0);
    }
    setActionInProgress(false);
}
 
Example 9
Source File: ListTagHandler.java    From zulip-android with Apache License 2.0 5 votes vote down vote up
/**
 * Opens a new list item.
 *
 * @param text
 */
public void openItem(final Editable text) {
    if (text.length() > 0 && text.charAt(text.length() - 1) != '\n') {
        text.append("\n");
    }
    final int len = text.length();
    text.setSpan(this, len, len, Spanned.SPAN_MARK_MARK);
}
 
Example 10
Source File: MessageLengthCounter.java    From BlackList with Apache License 2.0 5 votes vote down vote up
private void update(Editable messageText) {
    int messageLength = messageText.length();

    // is there unicode character in the message?
    boolean unicode = false;
    for (int i = 0; i < messageLength; i++) {
        char c = messageText.charAt(i);
        if (Character.UnicodeBlock.of(c) != Character.UnicodeBlock.BASIC_LATIN) {
            unicode = true;
            break;
        }
    }

    // get max length of sms part depending on encoding and full length
    int length1 = (unicode ? SMS_LENGTH_UNICODE : SMS_LENGTH);
    int length2 = (unicode ? SMS_LENGTH2_UNICODE : SMS_LENGTH2);
    int partMaxLength = (messageLength > length1 ? length2 : length1);
    // create current length status info
    int partsNumber = messageLength / partMaxLength + 1;
    int partLength = partMaxLength - messageLength % partMaxLength;
    // correct length info for second part
    if (partsNumber == 2 && partLength == partMaxLength) {
        partLength = length1 - (length1 - length2) * 2;
    }

    // show current length status info
    String counterText = "" + partLength + "/" + partsNumber;
    counterTextView.setText(counterText);
}
 
Example 11
Source File: CommonDeleteDialog.java    From AssistantBySDK with Apache License 2.0 5 votes vote down vote up
@Override
public void afterTextChanged(Editable s) {
	if(inputType==INPUT_ZH){
		int l=s.length();
		while(--l>=0){
			if(s.charAt(l)<0x4E00||s.charAt(l)>0x9FB0){
				s.delete(l, l+1);
			}
		}
	}
}
 
Example 12
Source File: PaddingChooser.java    From SuntimesWidget with GNU General Public License v3.0 5 votes vote down vote up
private void appendSeparator(Editable editable)
{
    if (editable.charAt(editable.length() - 1) != separator)
    {
        editable.append(separator);
    }
}
 
Example 13
Source File: BracketHighlighter.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
private void findOpen(char close, int selEnd) {
    Editable text = editText.getText();
    int cursor = selEnd - 1;
    int count = 1;
    boolean find = false;
    char open = getOpen(close);

    while (cursor > 0) {
        char chatAtCursor = text.charAt(cursor);
        if (chatAtCursor == open) {
            count--;
        } else if (chatAtCursor == close) {
            count++;
        }
        if (count == 0) {
            find = true;
            break;
        }
        cursor--;
    }
    BracketSpan[] spans = text.getSpans(0, text.length(), BracketSpan.class);
    for (BracketSpan span : spans) {
        text.removeSpan(span);
    }
    text.setSpan(new BracketSpan(codeTheme.getBracketColor(),
            codeTheme.getTextColor()), selEnd, selEnd + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    if (find) {
        text.setSpan(new BracketSpan(codeTheme.getBracketColor(),
                codeTheme.getTextColor()), cursor, cursor + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
}
 
Example 14
Source File: Html.java    From ForPDA with GNU General Public License v3.0 5 votes vote down vote up
private static void appendNewlines(Editable text, int minNewline) {
    final int len = text.length();
    if (len == 0) {
        return;
    }
    int existingNewlines = 0;
    for (int i = len - 1; i >= 0 && text.charAt(i) == '\n'; i--) {
        existingNewlines++;
    }
    for (int j = existingNewlines; j < minNewline; j++) {
        text.append("\n");
    }
}
 
Example 15
Source File: HtmlToSpannedConverter.java    From HtmlCompat with Apache License 2.0 5 votes vote down vote up
private void appendNewlines(Editable text, int minNewline) {
    final int len = text.length();
    if (len == 0) {
        return;
    }
    int existingNewlines = 0;
    for (int i = len - 1; i >= 0 && text.charAt(i) == '\n'; i--) {
        existingNewlines++;
    }
    for (int j = existingNewlines; j < minNewline; j++) {
        text.append("\n");
    }
}
 
Example 16
Source File: JotaTextKeyListener.java    From JotaTextEditor with Apache License 2.0 4 votes vote down vote up
@Override
public boolean onKeyDown(View view, Editable content, int keyCode, KeyEvent event) {
    boolean result = super.onKeyDown(view, content, keyCode, event);

    // auto indent
    if ( sAutoIndent && keyCode == KeyEvent.KEYCODE_ENTER ){

        int a = Selection.getSelectionStart(content);
        int b = Selection.getSelectionEnd(content);
        if ( a == b ){

            // search head of previous line
            int prev = a-2;
            while( prev >=0 && content.charAt(prev)!='\n' ){
                prev--;
            }
            prev ++;
            int pos = prev;
            while(  content.charAt(pos)==' ' || content.charAt(pos)=='\t' || content.charAt(pos)=='\u3000'){
                pos++;
            }
            int len = pos-prev;
            if ( len > 0  ){
                char [] dest = new char[len];
                content.getChars(prev, pos, dest, 0);

                content.replace(a,b, new String(dest) );
                Selection.setSelection(content, a+len);
            }
        }
    }
    if ( Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB ){
        if (keyCode == KEYCODE_FORWARD_DEL ) {
            if ( (event.getMetaState() & 512) == 0 ){       // workaround for Galaxy Note
                forwardDelete(view, content, keyCode, event);
                return true;
            }
        }
    }
    return result;
}
 
Example 17
Source File: CommentEditor.java    From Dashchan with Apache License 2.0 4 votes vote down vote up
private FormatResult formatSelectedTextOneLine(Editable editable, int what, Tag tag, int start, int end) {
	int newStart = -1;
	int newEnd = -1;
	int nextLine = start;
	String open = tag.open;
	String close = tag.close;
	for (int i = start; i <= end; i++) {
		char c = i == end ? '\n' : editable.charAt(i);
		if (c == '\n') {
			int lineStart = nextLine;
			int lineEnd = i;
			if (lineEnd > lineStart) {
				boolean mayCutStart = lineStart > start;
				boolean mayCutEnd = lineEnd < end;
				if (mayCutStart || mayCutEnd) {
					String line = editable.subSequence(lineStart, lineEnd).toString();
					boolean cutStart = mayCutStart && line.startsWith(open);
					boolean cutEnd = mayCutEnd && line.endsWith(close);
					int openLength = open.length();
					int closeLength = close.length();
					int similar = this.similar.get(what, -1);
					if (similar != -1) {
						Tag similarTag = tags.get(similar);
						if (cutStart && line.startsWith(similarTag.open) &&
								!line.startsWith(open + similarTag.open)) {
							openLength = similarTag.open.length();
						}
						if (cutEnd && line.endsWith(similarTag.close) &&
								!line.endsWith(similarTag.close + close)) {
							closeLength = similarTag.close.length();
						}
					}
					if (mayCutStart && mayCutEnd) {
						if (cutStart && cutEnd) {
							// Handle lines with open tag at start and close tag at end
							lineStart += openLength;
							lineEnd -= closeLength;
						}
					} else {
						if (cutStart) {
							lineStart += openLength;
						}
						if (cutEnd) {
							lineEnd -= closeLength;
						}
					}
				}
				FormatResult result = formatSelectedTextLineDirectly(editable, what, tag, lineStart, lineEnd);
				int startShift = result.start - lineStart;
				int endShift = result.end - lineEnd;
				end += startShift + endShift;
				i += startShift + endShift;
				if (newStart == -1) {
					newStart = result.start;
					start += startShift; // Count first start shift
				}
				newEnd = result.end;
			} else {
				if (newStart == -1) {
					newStart = start;
				}
				newEnd = end;
			}
			nextLine = i + 1;
		}
	}
	return new FormatResult(newStart, newEnd);
}
 
Example 18
Source File: BoletoBancarioTextWatcher.java    From canarinho with Apache License 2.0 4 votes vote down vote up
private boolean ehTributo(Editable e) {
    return e.charAt(0) == '8';
}
 
Example 19
Source File: RecipientEditTextView.java    From ChipsLibrary with Apache License 2.0 4 votes vote down vote up
void handlePendingChips()
{
if(getViewWidth()<=0)
  // The widget has not been sized yet.
  // This will be called as a result of onSizeChanged
  // at a later point.
  return;
if(mPendingChipsCount<=0)
  return;
synchronized(mPendingChips)
  {
  final Editable editable=getText();
  // Tokenize!
  if(mPendingChipsCount<=MAX_CHIPS_PARSED)
    {
    for(int i=0;i<mPendingChips.size();i++)
      {
      final String current=mPendingChips.get(i);
      final int tokenStart=editable.toString().indexOf(current);
      // Always leave a space at the end between tokens.
      int tokenEnd=tokenStart+current.length()-1;
      if(tokenStart>=0)
        {
        // When we have a valid token, include it with the token
        // to the left.
        if(tokenEnd<editable.length()-2&&editable.charAt(tokenEnd)==COMMIT_CHAR_COMMA)
          tokenEnd++;
        createReplacementChip(tokenStart,tokenEnd,editable,i<CHIP_LIMIT||!mShouldShrink);
        }
      mPendingChipsCount--;
      }
    sanitizeEnd();
    }
  else mNoChips=true;
  if(mTemporaryRecipients!=null&&mTemporaryRecipients.size()>0&&mTemporaryRecipients.size()<=RecipientAlternatesAdapter.MAX_LOOKUPS)
    {
    if(hasFocus()||mTemporaryRecipients.size()<CHIP_LIMIT)
      {
      new RecipientReplacementTask().execute();
      mTemporaryRecipients=null;
      }
    else
      {
      // Create the "more" chip
      mIndividualReplacements=new IndividualReplacementTask();
      mIndividualReplacements.execute(new ArrayList<DrawableRecipientChip>(mTemporaryRecipients.subList(0,CHIP_LIMIT)));
      if(mTemporaryRecipients.size()>CHIP_LIMIT)
        mTemporaryRecipients=new ArrayList<DrawableRecipientChip>(mTemporaryRecipients.subList(CHIP_LIMIT,mTemporaryRecipients.size()));
      else mTemporaryRecipients=null;
      createMoreChip();
      }
    }
  else
    {
    // There are too many recipients to look up, so just fall back
    // to showing addresses for all of them.
    mTemporaryRecipients=null;
    createMoreChip();
    }
  mPendingChipsCount=0;
  mPendingChips.clear();
  }
}
 
Example 20
Source File: HtmlTagHandler.java    From android-discourse with Apache License 2.0 4 votes vote down vote up
@Override
public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
    if (tag.equalsIgnoreCase("ul")) {
        if (opening) {
            lists.push(tag);
        } else {
            lists.pop();
        }
    } else if (tag.equalsIgnoreCase("ol")) {
        if (opening) {
            lists.push(tag);
            olNextIndex.push(Integer.valueOf(1)).toString();// TODO: add support for lists starting other index than 1
        } else {
            lists.pop();
            olNextIndex.pop().toString();
        }
    } else if (tag.equalsIgnoreCase("li")) {
        if (opening) {
            if (output.length() > 0 && output.charAt(output.length() - 1) != '\n') {
                output.append("\n");
            }
            String parentList = lists.peek();
            if (parentList.equalsIgnoreCase("ol")) {
                start(output, new Ol());
                output.append(olNextIndex.peek().toString() + ". ");
                olNextIndex.push(Integer.valueOf(olNextIndex.pop().intValue() + 1));
            } else if (parentList.equalsIgnoreCase("ul")) {
                start(output, new Ul());
            }
        } else {
            if (lists.peek().equalsIgnoreCase("ul")) {
                if (output.charAt(output.length() - 1) != '\n') {
                    output.append("\n");
                }
                // Nested BulletSpans increases distance between bullet and text, so we must prevent it.
                int bulletMargin = indent;
                if (lists.size() > 1) {
                    bulletMargin = indent - bullet.getLeadingMargin(true);
                    if (lists.size() > 2) {
                        // This get's more complicated when we add a LeadingMarginSpan into the same line:
                        // we have also counter it's effect to BulletSpan
                        bulletMargin -= (lists.size() - 2) * listItemIndent;
                    }
                }
                BulletSpan newBullet = new BulletSpan(bulletMargin);
                end(output, Ul.class, new LeadingMarginSpan.Standard(listItemIndent * (lists.size() - 1)), newBullet);
            } else if (lists.peek().equalsIgnoreCase("ol")) {
                if (output.charAt(output.length() - 1) != '\n') {
                    output.append("\n");
                }
                int numberMargin = listItemIndent * (lists.size() - 1);
                if (lists.size() > 2) {
                    // Same as in ordered lists: counter the effect of nested Spans
                    numberMargin -= (lists.size() - 2) * listItemIndent;
                }
                end(output, Ol.class, new LeadingMarginSpan.Standard(numberMargin));
            }
        }
    } else if (tag.equalsIgnoreCase("code")) {
        if (opening) {
            output.setSpan(new TypefaceSpan("monospace"), output.length(), output.length(), Spannable.SPAN_MARK_MARK);
        } else {
            L.d("Code tag encountered");
            Object obj = getLast(output, TypefaceSpan.class);
            int where = output.getSpanStart(obj);
            output.setSpan(new TypefaceSpan("monospace"), where, output.length(), 0);
            output.setSpan(new BackgroundColorSpan(Color.parseColor("#f1f1ff")), where, output.length(), 0);
        }
    } else {
        if (opening)
            L.d("Found an unsupported tag " + tag);
    }
}