Example usage for android.text.style BackgroundColorSpan BackgroundColorSpan

List of usage examples for android.text.style BackgroundColorSpan BackgroundColorSpan

Introduction

In this page you can find the example usage for android.text.style BackgroundColorSpan BackgroundColorSpan.

Prototype

public BackgroundColorSpan(@NonNull Parcel src) 

Source Link

Document

Creates a BackgroundColorSpan from a parcel.

Usage

From source file:org.miaowo.miaowo.util.Html.java

private static void endCssStyle(Editable text) {
    Strikethrough s = getLast(text, Strikethrough.class);
    if (s != null) {
        setSpanFromMark(text, s, new StrikethroughSpan());
    }/*from  w  w  w . j  a  v a  2  s . com*/

    Background b = getLast(text, Background.class);
    if (b != null) {
        setSpanFromMark(text, b, new BackgroundColorSpan(b.mBackgroundColor));
    }

    Foreground f = getLast(text, Foreground.class);
    if (f != null) {
        setSpanFromMark(text, f, new ForegroundColorSpan(f.mForegroundColor));
    }
}

From source file:com.nttec.everychan.ui.gallery.GalleryActivity.java

private Spanned getSpannedText(String message) {
    message = " " + message + " ";
    SpannableStringBuilder spanned = new SpannableStringBuilder(message);
    for (Object span : new Object[] { new ForegroundColorSpan(Color.WHITE),
            new BackgroundColorSpan(Color.parseColor("#88000000")) }) {
        spanned.setSpan(span, 0, message.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }/*from w w  w .j ava  2 s  .c o m*/
    return spanned;
}

From source file:com.strathclyde.highlightingkeyboard.SoftKeyboardService.java

/**
 * Handles the manual selection of suggestions from the suggestion bar
 * @param index the position of the suggestion in the suggestion list
 *///w w  w.j av  a2 s .  c  o  m
public void pickSuggestionManually(int index) {
    if (mCompletionOn && mCompletions != null && index >= 0 && index < mCompletions.length) {
        CompletionInfo ci = mCompletions[index];
        ic.commitCompletion(ci);
        if (mCandidateView != null) {
            mCandidateView.clear();
        }
        updateShiftKeyState(getCurrentInputEditorInfo());
    } else if (mComposing.length() >= 0) {

        String picked;
        if (!replacemode)
            picked = suggestions.get(index) + " ";
        else
            picked = suggestions.get(index);

        //Log.i("Suggestion picked 2", picked);

        //ic.commitText(picked, picked.length());

        getCurrentInputEditorInfo();

        //colour the text according to user preferences
        SpannableString text = new SpannableString(picked);
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        if (sharedPrefs.getBoolean("suggestion_highlight", false))
            text.setSpan(new BackgroundColorSpan(suggestion), 0, picked.length() - 1,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        currentSession.nSuggestionsPicked++;

        if (replacemode) {
            replacemode = false;
            //remove from list of autocorrected words.
            //Log.i("PickSuggestion", "Removed "+autocorrected_words.remove(text.toString()));

            //find the current word
            extr = ic.getExtractedText(new ExtractedTextRequest(), 0);
            WordDetails w = findWord(extr.selectionStart, extr.text);
            //Log.i("FindWord", w.word+", "+w.wordStart+" - "+w.wordEnd);
            ic.setComposingRegion(w.wordStart, w.wordEnd);
            text.setSpan(null, 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            /*
            //clear any spans       
            BackgroundColorSpan[] spans=(new SpannableString(extr.text.toString())).getSpans(w.wordStart, w.wordEnd, BackgroundColorSpan.class);
            for(int i=0; i<spans.length; i++){
              text.removeSpan(spans[i]);
            }*/

            //commit the update
            ic.commitText(text, 1);

        } else
            ic.commitText(text, picked.length());

        coreEngine.resetCoreString();
        coreEngine.insertText(picked);
        mComposing.setLength(0);
        updateCandidates();
    }
}

From source file:cgeo.geocaching.CacheDetailActivity.java

private static void fixTextColor(final Spannable spannable, final int backgroundColor) {
    final ForegroundColorSpan[] spans = spannable.getSpans(0, spannable.length(), ForegroundColorSpan.class);

    for (final ForegroundColorSpan span : spans) {
        if (ColorUtils.getContrastRatio(span.getForegroundColor(), backgroundColor) < CONTRAST_THRESHOLD) {
            final int start = spannable.getSpanStart(span);
            final int end = spannable.getSpanEnd(span);

            //  Assuming that backgroundColor can be either white or black,
            // this will set opposite background color (white for black and black for white)
            spannable.setSpan(new BackgroundColorSpan(backgroundColor ^ 0x00ffffff), start, end,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }// w w w  .  j a  v  a2  s  . c o m
    }
}

From source file:com.strathclyde.highlightingkeyboard.SoftKeyboardService.java

/**
 * handle the receipt of suggestions from the spell checker
 * colour the text in the editor as required
 * pass information to the keyboard view so it can draw the colour bar
 * initiate audio and haptic feedback as required
 *///from   ww w . ja va2 s.co  m
@Override
public void onGetSuggestions(SuggestionsInfo[] results) {
    // TODO Auto-generated method stub
    int colortype = -1;
    final StringBuilder sb = new StringBuilder();

    if (updateSuggestionList) {
        updateSuggestionList = false;
        ArrayList<String> s = new ArrayList<String>();
        for (int i = 0; i < results.length; ++i) {
            final int length = results[i].getSuggestionsCount();
            for (int j = 0; j < length; ++j) {
                s.add(results[i].getSuggestionAt(j));
            }
        }
        updateSuggestionListWithSpellChecker(s);
    } else {

        for (int i = 0; i < results.length; ++i) {
            // Returned suggestions are contained in SuggestionsInfo

            final int len = results[i].getSuggestionsCount();
            sb.append("Suggestion Attribs: " + results[i].getSuggestionsAttributes());
            if ((results[i].getSuggestionsAttributes()
                    & SuggestionsInfo.RESULT_ATTR_IN_THE_DICTIONARY) == SuggestionsInfo.RESULT_ATTR_IN_THE_DICTIONARY) {
                sb.append("The word was found in the dictionary\n");
                mInputView.wordcompletedtype = 3;
            } else {

                if ((results[i].getSuggestionsAttributes()
                        & SuggestionsInfo.RESULT_ATTR_LOOKS_LIKE_TYPO) == SuggestionsInfo.RESULT_ATTR_LOOKS_LIKE_TYPO) {
                    if ((results[i].getSuggestionsAttributes()
                            & SuggestionsInfo.RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS) == SuggestionsInfo.RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS) {
                        colortype = 1; //yellow
                        mInputView.wordcompletedtype = 1;
                        sb.append("There are strong candidates for this word\n");
                        currentSession.nLowErrors++;
                    } else {
                        colortype = 2; //red
                        mInputView.wordcompletedtype = 2;
                        sb.append("The word looks like a typo\n");
                        currentSession.nHighErrors++;

                    }
                }

            }

            sb.append("\n--These are the suggestions--\n");
            for (int j = 0; j < len; ++j) {
                sb.append("," + results[i].getSuggestionAt(j));
            }
            sb.append(" (" + len + ")");
        }
        //Log.i("Spelling suggestions", sb.toString());

        //this comes after a word separator, hence just add 1 to the cursor
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

        SpannableString text = new SpannableString(mComposingTemp);

        if (sharedPrefs.getBoolean("highlightwords", true)) {
            switch (colortype) {
            case 1:
                text.setSpan(new BackgroundColorSpan(small_err), 0, mComposingTemp.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                break;
            case 2:
                text.setSpan(new BackgroundColorSpan(big_err), 0, mComposingTemp.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                break;
            default:
                break;
            }
        }

        if (sharedPrefs.getBoolean("autocorrect", true) && mInputView.wordcompletedtype == 1) //handle autocorrection
        {
            SpannableString autoc = autocorrect(results);
            autocorrected_words.put(autoc.toString(), text.toString()); //autocorrected word, original input
            //Log.i("Autocorrecting","Key= "+autoc.toString()+", Value= "+text.toString());
            text = autoc;
            if (sharedPrefs.getBoolean("highlightwords", true))
                text.setSpan(new BackgroundColorSpan(autocorrect), 0, text.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            mInputView.wordcompletedtype = 4;
        } else //autocorrection is turned off
        {
            if (!sharedPrefs.getBoolean("autocorrect", true) && colortype >= 1) //a mistake word
            {
                //Log.i("OnGetSentenceSuggestions","Key= "+text.toString()+", Value= "+text.toString());
                //no autocorrects, just put the word in and itself as the replacement
                autocorrected_words.put(text.toString(), text.toString());
            }
        }

        if (sharedPrefs.getBoolean("vibrator", false)) {
            Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            final int on_time = Integer.parseInt(sharedPrefs.getString("shortvibe", "35"));

            switch (mInputView.wordcompletedtype) {
            case 1: //small err
                // Vibrate for 300 milliseconds
                v.vibrate(on_time);
                break;
            case 2: //big err
                //v.vibrate(Integer.parseInt(sharedPrefs.getString("longvibe", "300")));
                v.vibrate(new long[] { 0, on_time, 200, on_time }, -1);
                break;
            case 4: //autocorr
                v.vibrate(on_time);
                break;
            default:
                break;

            }
        }

        if (sharedPrefs.getBoolean("audio", false)) {
            final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
            switch (mInputView.wordcompletedtype) {
            case 1: //small err
                tg.startTone(ToneGenerator.TONE_PROP_BEEP);
                break;
            case 2: //big err
                tg.startTone(ToneGenerator.TONE_PROP_BEEP2);
                break;
            case 4: //autocorr
                tg.startTone(ToneGenerator.TONE_PROP_BEEP);
                break;
            default:
                break;

            }
        }

        mInputView.invalidateAllKeys();
        ic.commitText(text, 1);
        sendKey(wordSeparatorKeyCode);
        coreEngine.resetCoreString();
        updateCandidates();
    }

}

From source file:com.nttec.everychan.ui.presentation.BoardFragment.java

private void initSearchBar() {
    if (searchBarInitialized)
        return;/*from  w  w w .  ja v  a  2 s  .  c  om*/
    final EditText field = (EditText) searchBarView.findViewById(R.id.board_search_field);
    final TextView results = (TextView) searchBarView.findViewById(R.id.board_search_result);
    if (pageType == TYPE_POSTSLIST) {
        field.setHint(R.string.search_bar_in_thread_hint);
    }
    final View.OnClickListener searchOnClickListener = new View.OnClickListener() {
        private int lastFound = -1;

        @Override
        public void onClick(View v) {
            if (v != null && v.getId() == R.id.board_search_close) {
                searchHighlightActive = false;
                adapter.notifyDataSetChanged();
                searchBarView.setVisibility(View.GONE);
            } else if (listView != null && listView.getChildCount() > 0 && adapter != null
                    && cachedSearchResults != null) {
                boolean atEnd = listView.getChildAt(listView.getChildCount() - 1).getTop()
                        + listView.getChildAt(listView.getChildCount() - 1).getHeight() == listView.getHeight();

                View topView = listView.getChildAt(0);
                if ((v == null || v.getId() == R.id.board_search_previous) && topView.getTop() < 0
                        && listView.getChildCount() > 1)
                    topView = listView.getChildAt(1);
                int currentListPosition = listView.getPositionForView(topView);

                int newResultIndex = Collections.binarySearch(cachedSearchResults, currentListPosition);
                if (newResultIndex >= 0) {
                    if (v != null) {
                        if (v.getId() == R.id.board_search_next)
                            ++newResultIndex;
                        else if (v.getId() == R.id.board_search_previous)
                            --newResultIndex;
                    }
                } else {
                    newResultIndex = -newResultIndex - 1;
                    if (v != null && v.getId() == R.id.board_search_previous)
                        --newResultIndex;
                }
                while (newResultIndex < 0)
                    newResultIndex += cachedSearchResults.size();
                newResultIndex %= cachedSearchResults.size();

                if (v != null && v.getId() == R.id.board_search_next && lastFound == newResultIndex && atEnd)
                    newResultIndex = 0;
                lastFound = newResultIndex;

                listView.setSelection(cachedSearchResults.get(newResultIndex));
                results.setText((newResultIndex + 1) + "/" + cachedSearchResults.size());
            }
        }
    };
    for (int id : new int[] { R.id.board_search_close, R.id.board_search_previous, R.id.board_search_next }) {
        searchBarView.findViewById(id).setOnClickListener(searchOnClickListener);
    }
    field.setOnKeyListener(new View.OnKeyListener() {
        private boolean searchUsingChan() {
            if (pageType != TYPE_THREADSLIST)
                return false;
            if (presentationModel != null)
                if (presentationModel.source != null)
                    if (presentationModel.source.boardModel != null)
                        if (!presentationModel.source.boardModel.searchAllowed)
                            return false;
            return true;
        }

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                if (searchUsingChan()) {
                    UrlPageModel model = new UrlPageModel();
                    model.chanName = chan.getChanName();
                    model.type = UrlPageModel.TYPE_SEARCHPAGE;
                    model.boardName = tabModel.pageModel.boardName;
                    model.searchRequest = field.getText().toString();
                    UrlHandler.open(model, activity);
                } else {
                    int highlightColor = ThemeUtils.getThemeColor(activity.getTheme(),
                            R.attr.searchHighlightBackground, Color.RED);
                    String request = field.getText().toString().toLowerCase(Locale.US);

                    if (cachedSearchRequest == null || !request.equals(cachedSearchRequest)) {
                        cachedSearchRequest = request;
                        cachedSearchResults = new ArrayList<Integer>();
                        cachedSearchHighlightedSpanables = new SparseArray<Spanned>();
                        List<PresentationItemModel> safePresentationList = presentationModel
                                .getSafePresentationList();
                        if (safePresentationList != null) {
                            for (int i = 0; i < safePresentationList.size(); ++i) {
                                PresentationItemModel model = safePresentationList.get(i);
                                if (model.hidden && !staticSettings.showHiddenItems)
                                    continue;
                                String comment = model.spannedComment.toString().toLowerCase(Locale.US)
                                        .replace('\n', ' ');
                                List<Integer> altFoundPositions = null;
                                if (model.floating) {
                                    int floatingpos = FlowTextHelper.getFloatingPosition(model.spannedComment);
                                    if (floatingpos != -1 && floatingpos < model.spannedComment.length()
                                            && model.spannedComment.charAt(floatingpos) == '\n') {
                                        String altcomment = comment.substring(0, floatingpos)
                                                + comment.substring(floatingpos + 1,
                                                        Math.min(model.spannedComment.length(),
                                                                floatingpos + request.length()));
                                        int start = 0;
                                        int curpos;
                                        while (start < altcomment.length()
                                                && (curpos = altcomment.indexOf(request, start)) != -1) {
                                            if (altFoundPositions == null)
                                                altFoundPositions = new ArrayList<Integer>();
                                            altFoundPositions.add(curpos);
                                            start = curpos + request.length();
                                        }
                                    }
                                }

                                if (comment.contains(request) || altFoundPositions != null) {
                                    cachedSearchResults.add(Integer.valueOf(i));
                                    SpannableStringBuilder spannedHighlited = new SpannableStringBuilder(
                                            safePresentationList.get(i).spannedComment);
                                    int start = 0;
                                    int curpos;
                                    while (start < comment.length()
                                            && (curpos = comment.indexOf(request, start)) != -1) {
                                        start = curpos + request.length();
                                        if (altFoundPositions != null
                                                && Collections.binarySearch(altFoundPositions, curpos) >= 0)
                                            continue;
                                        spannedHighlited.setSpan(new BackgroundColorSpan(highlightColor),
                                                curpos, curpos + request.length(),
                                                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    }
                                    if (altFoundPositions != null) {
                                        for (Integer pos : altFoundPositions) {
                                            spannedHighlited.setSpan(new BackgroundColorSpan(highlightColor),
                                                    pos, pos + request.length(),
                                                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                        }
                                    }
                                    cachedSearchHighlightedSpanables.put(i, spannedHighlited);
                                }
                            }
                        }
                    }

                    if (cachedSearchResults.size() == 0) {
                        Toast.makeText(activity, R.string.notification_not_found, Toast.LENGTH_LONG).show();
                    } else {
                        boolean firstTime = !searchHighlightActive;
                        searchHighlightActive = true;
                        adapter.notifyDataSetChanged();
                        searchBarView.findViewById(R.id.board_search_next).setVisibility(View.VISIBLE);
                        searchBarView.findViewById(R.id.board_search_previous).setVisibility(View.VISIBLE);
                        searchBarView.findViewById(R.id.board_search_result).setVisibility(View.VISIBLE);
                        searchOnClickListener
                                .onClick(firstTime ? null : searchBarView.findViewById(R.id.board_search_next));
                    }
                }
                try {
                    InputMethodManager imm = (InputMethodManager) activity
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(field.getWindowToken(), 0);
                } catch (Exception e) {
                    Logger.e(TAG, e);
                }
                return true;
            }
            return false;
        }
    });
    field.addTextChangedListener(new OnSearchTextChangedListener(this));
    field.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
    if (resources.getDimensionPixelSize(R.dimen.panel_height) < field.getMeasuredHeight())
        searchBarView.getLayoutParams().height = field.getMeasuredHeight();
    searchBarInitialized = true;
}