Example usage for android.text Editable getSpanFlags

List of usage examples for android.text Editable getSpanFlags

Introduction

In this page you can find the example usage for android.text Editable getSpanFlags.

Prototype

public int getSpanFlags(Object tag);

Source Link

Document

Return the flags that were specified when Spannable#setSpan was used to attach the specified markup object, or 0 if the specified object has not been attached.

Usage

From source file:org.mozilla.focus.widget.InlineAutocompleteEditText.java

private static boolean hasCompositionString(Editable content) {
    Object[] spans = content.getSpans(0, content.length(), Object.class);

    if (spans != null) {
        for (Object span : spans) {
            if ((content.getSpanFlags(span) & Spanned.SPAN_COMPOSING) != 0) {
                // Found composition string.
                return true;
            }//w  w  w . j a v  a2s .c  o  m
        }
    }

    return false;
}

From source file:com.taobao.weex.dom.WXTextDomObject.java

/**
 * Truncate the source span to the specified lines.
 * Caller of this method must ensure that the lines of text is <strong>greater than desired lines and need truncate</strong>.
 * Otherwise, unexpected behavior may happen.
 * @param source The source span.//from   www . jav  a2s  . c  om
 * @param paint the textPaint
 * @param desired specified lines.
 * @param truncateAt truncate method, null value means clipping overflow text directly, non-null value means using ellipsis strategy to clip
 * @return The spans after clipped.
 */
private @NonNull Spanned truncate(@Nullable Editable source, @NonNull TextPaint paint, int desired,
        @Nullable TextUtils.TruncateAt truncateAt) {
    Spanned ret = new SpannedString("");
    if (!TextUtils.isEmpty(source) && source.length() > 0) {
        if (truncateAt != null) {
            source.append(ELLIPSIS);
            Object[] spans = source.getSpans(0, source.length(), Object.class);
            for (Object span : spans) {
                int start = source.getSpanStart(span);
                int end = source.getSpanEnd(span);
                if (start == 0 && end == source.length() - 1) {
                    source.removeSpan(span);
                    source.setSpan(span, 0, source.length(), source.getSpanFlags(span));
                }
            }
        }

        StaticLayout layout;
        int startOffset;

        while (source.length() > 1) {
            startOffset = source.length() - 1;
            if (truncateAt != null) {
                startOffset -= 1;
            }
            source.delete(startOffset, startOffset + 1);
            layout = new StaticLayout(source, paint, desired, Layout.Alignment.ALIGN_NORMAL, 1, 0, false);
            if (layout.getLineCount() <= 1) {
                ret = source;
                break;
            }
        }
    }
    return ret;
}

From source file:org.mozilla.focus.widget.InlineAutocompleteEditText.java

/**
 * Add autocomplete text based on the result URI.
 *
 * @param result Result URI to be turned into autocomplete text
 *//*from  ww  w  .ja  v a2  s  .  c  om*/
public final void onAutocomplete(final String result) {
    // If mDiscardAutoCompleteResult is true, we temporarily disabled
    // autocomplete (due to backspacing, etc.) and we should bail early.
    if (mDiscardAutoCompleteResult) {
        return;
    }

    if (!isEnabled() || result == null) {
        mAutoCompleteResult = "";
        return;
    }

    final Editable text = getText();
    final int textLength = text.length();
    final int resultLength = result.length();
    final int autoCompleteStart = text.getSpanStart(AUTOCOMPLETE_SPAN);
    mAutoCompleteResult = result;

    if (autoCompleteStart > -1) {
        // Autocomplete text already exists; we should replace existing autocomplete text.

        // If the result and the current text don't have the same prefixes,
        // the result is stale and we should wait for the another result to come in.
        if (!TextUtils.regionMatches(result, 0, text, 0, autoCompleteStart)) {
            return;
        }

        beginSettingAutocomplete();

        // Replace the existing autocomplete text with new one.
        // replace() preserves the autocomplete spans that we set before.
        text.replace(autoCompleteStart, textLength, result, autoCompleteStart, resultLength);

        // Reshow the cursor if there is no longer any autocomplete text.
        if (autoCompleteStart == resultLength) {
            setCursorVisible(true);
        }

        endSettingAutocomplete();

    } else {
        // No autocomplete text yet; we should add autocomplete text

        // If the result prefix doesn't match the current text,
        // the result is stale and we should wait for the another result to come in.
        if (resultLength <= textLength || !TextUtils.regionMatches(result, 0, text, 0, textLength)) {
            return;
        }

        final Object[] spans = text.getSpans(textLength, textLength, Object.class);
        final int[] spanStarts = new int[spans.length];
        final int[] spanEnds = new int[spans.length];
        final int[] spanFlags = new int[spans.length];

        // Save selection/composing span bounds so we can restore them later.
        for (int i = 0; i < spans.length; i++) {
            final Object span = spans[i];
            final int spanFlag = text.getSpanFlags(span);

            // We don't care about spans that are not selection or composing spans.
            // For those spans, spanFlag[i] will be 0 and we don't restore them.
            if ((spanFlag & Spanned.SPAN_COMPOSING) == 0 && (span != Selection.SELECTION_START)
                    && (span != Selection.SELECTION_END)) {
                continue;
            }

            spanStarts[i] = text.getSpanStart(span);
            spanEnds[i] = text.getSpanEnd(span);
            spanFlags[i] = spanFlag;
        }

        beginSettingAutocomplete();

        // First add trailing text.
        text.append(result, textLength, resultLength);

        // Restore selection/composing spans.
        for (int i = 0; i < spans.length; i++) {
            final int spanFlag = spanFlags[i];
            if (spanFlag == 0) {
                // Skip if the span was ignored before.
                continue;
            }
            text.setSpan(spans[i], spanStarts[i], spanEnds[i], spanFlag);
        }

        // Mark added text as autocomplete text.
        for (final Object span : mAutoCompleteSpans) {
            text.setSpan(span, textLength, resultLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        // Hide the cursor.
        setCursorVisible(false);

        // Make sure the autocomplete text is visible. If the autocomplete text is too
        // long, it would appear the cursor will be scrolled out of view. However, this
        // is not the case in practice, because EditText still makes sure the cursor is
        // still in view.
        bringPointIntoView(resultLength);

        endSettingAutocomplete();
    }

    announceForAccessibility(text.toString());
}

From source file:com.irccloud.android.activity.MainActivity.java

@SuppressLint("NewApi")
@SuppressWarnings({ "deprecation", "unchecked" })
@Override/*from  w  w w . j ava  2 s  .  co  m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    suggestionsTimer = new Timer("suggestions-timer");
    countdownTimer = new Timer("messsage-countdown-timer");

    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    registerReceiver(screenReceiver, filter);

    if (Build.VERSION.SDK_INT >= 21) {
        Bitmap cloud = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        if (cloud != null) {
            setTaskDescription(new ActivityManager.TaskDescription(getResources().getString(R.string.app_name),
                    cloud, 0xFFF2F7FC));
            cloud.recycle();
        }
    }
    setContentView(R.layout.activity_message);
    try {
        setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
    } catch (Throwable t) {
    }

    suggestionsAdapter = new SuggestionsAdapter();
    progressBar = (ProgressBar) findViewById(R.id.progress);
    errorMsg = (TextView) findViewById(R.id.errorMsg);
    buffersListView = findViewById(R.id.BuffersList);
    messageContainer = (LinearLayout) findViewById(R.id.messageContainer);
    drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);

    redColor = getResources().getColor(R.color.highlight_red);
    blueColor = getResources().getColor(R.color.dark_blue);

    messageTxt = (ActionEditText) findViewById(R.id.messageTxt);
    messageTxt.setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (sendBtn.isEnabled()
                    && NetworkConnection.getInstance().getState() == NetworkConnection.STATE_CONNECTED
                    && event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER
                    && messageTxt.getText() != null && messageTxt.getText().length() > 0) {
                sendBtn.setEnabled(false);
                new SendTask().execute((Void) null);
            } else if (keyCode == KeyEvent.KEYCODE_TAB) {
                if (event.getAction() == KeyEvent.ACTION_DOWN)
                    nextSuggestion();
                return true;
            }
            return false;
        }
    });
    messageTxt.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (drawerLayout != null && v == messageTxt && hasFocus) {
                drawerLayout.closeDrawers();
                update_suggestions(false);
            } else if (!hasFocus) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        suggestionsContainer.setVisibility(View.INVISIBLE);
                    }
                });
            }
        }
    });
    messageTxt.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (drawerLayout != null) {
                drawerLayout.closeDrawers();
            }
        }
    });
    messageTxt.setOnEditorActionListener(new OnEditorActionListener() {
        public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
            if (sendBtn.isEnabled()
                    && NetworkConnection.getInstance().getState() == NetworkConnection.STATE_CONNECTED
                    && actionId == EditorInfo.IME_ACTION_SEND && messageTxt.getText() != null
                    && messageTxt.getText().length() > 0) {
                sendBtn.setEnabled(false);
                new SendTask().execute((Void) null);
            }
            return true;
        }
    });
    textWatcher = new TextWatcher() {
        public void afterTextChanged(Editable s) {
            Object[] spans = s.getSpans(0, s.length(), Object.class);
            for (Object o : spans) {
                if (((s.getSpanFlags(o) & Spanned.SPAN_COMPOSING) != Spanned.SPAN_COMPOSING)
                        && (o.getClass() == StyleSpan.class || o.getClass() == ForegroundColorSpan.class
                                || o.getClass() == BackgroundColorSpan.class
                                || o.getClass() == UnderlineSpan.class || o.getClass() == URLSpan.class)) {
                    s.removeSpan(o);
                }
            }
            if (s.length() > 0
                    && NetworkConnection.getInstance().getState() == NetworkConnection.STATE_CONNECTED) {
                sendBtn.setEnabled(true);
                if (Build.VERSION.SDK_INT >= 11)
                    sendBtn.setAlpha(1);
            } else {
                sendBtn.setEnabled(false);
                if (Build.VERSION.SDK_INT >= 11)
                    sendBtn.setAlpha(0.5f);
            }
            String text = s.toString();
            if (text.endsWith("\t")) { //Workaround for Swype
                text = text.substring(0, text.length() - 1);
                messageTxt.setText(text);
                nextSuggestion();
            } else if (suggestionsContainer != null && suggestionsContainer.getVisibility() == View.VISIBLE) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        update_suggestions(false);
                    }
                });
            } else {
                if (suggestionsTimer != null) {
                    if (suggestionsTimerTask != null)
                        suggestionsTimerTask.cancel();
                    suggestionsTimerTask = new TimerTask() {
                        @Override
                        public void run() {
                            Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
                            update_suggestions(false);
                        }
                    };
                    suggestionsTimer.schedule(suggestionsTimerTask, 250);
                }
            }
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    };
    messageTxt.addTextChangedListener(textWatcher);
    sendBtn = findViewById(R.id.sendBtn);
    sendBtn.setFocusable(false);
    sendBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (NetworkConnection.getInstance().getState() == NetworkConnection.STATE_CONNECTED)
                new SendTask().execute((Void) null);
        }
    });

    photoBtn = findViewById(R.id.photoBtn);
    if (photoBtn != null) {
        photoBtn.setFocusable(false);
        photoBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                insertPhoto();
            }
        });
    }
    userListView = findViewById(R.id.usersListFragment);

    View v = getLayoutInflater().inflate(R.layout.actionbar_messageview, null);
    v.findViewById(R.id.actionTitleArea).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            show_topic_popup();
        }
    });

    if (drawerLayout != null) {
        if (findViewById(R.id.usersListFragment2) == null) {
            upDrawable = new DrawerArrowDrawable(this);
            greyColor = upDrawable.getColor();
            ((Toolbar) findViewById(R.id.toolbar)).setNavigationIcon(upDrawable);
            ((Toolbar) findViewById(R.id.toolbar)).setNavigationContentDescription("Show navigation drawer");
            drawerLayout.setDrawerListener(mDrawerListener);
            if (refreshUpIndicatorTask != null)
                refreshUpIndicatorTask.cancel(true);
            refreshUpIndicatorTask = new RefreshUpIndicatorTask();
            refreshUpIndicatorTask.execute((Void) null);
        }
    }
    messageTxt.setDrawerLayout(drawerLayout);

    title = (TextView) v.findViewById(R.id.title);
    subtitle = (TextView) v.findViewById(R.id.subtitle);
    key = (ImageView) v.findViewById(R.id.key);
    getSupportActionBar().setCustomView(v);
    getSupportActionBar().setDisplayShowCustomEnabled(true);
    getSupportActionBar().setDisplayShowTitleEnabled(false);

    if (savedInstanceState != null && savedInstanceState.containsKey("cid")) {
        server = ServersDataSource.getInstance().getServer(savedInstanceState.getInt("cid"));
        buffer = BuffersDataSource.getInstance().getBuffer(savedInstanceState.getInt("bid"));
        backStack = (ArrayList<Integer>) savedInstanceState.getSerializable("backStack");
    }

    if (savedInstanceState != null && savedInstanceState.containsKey("imagecaptureuri"))
        imageCaptureURI = Uri.parse(savedInstanceState.getString("imagecaptureuri"));
    else
        imageCaptureURI = null;

    ConfigInstance config = (ConfigInstance) getLastCustomNonConfigurationInstance();
    if (config != null) {
        imgurTask = config.imgurUploadTask;
        fileUploadTask = config.fileUploadTask;
    }

    drawerLayout.setScrimColor(0);
    drawerLayout.closeDrawers();

    getSupportActionBar().setElevation(0);
}