Example usage for android.text SpannableStringBuilder setSpan

List of usage examples for android.text SpannableStringBuilder setSpan

Introduction

In this page you can find the example usage for android.text SpannableStringBuilder setSpan.

Prototype

public void setSpan(Object what, int start, int end, int flags) 

Source Link

Document

Mark the specified range of text with the specified object.

Usage

From source file:de.tum.in.tumcampus.auxiliary.calendar.DayView.java

/**
 * Return the layout for a numbered event. Create it if not already existing
 *//*from w w w .  jav  a 2s. c om*/
private StaticLayout getEventLayout(StaticLayout[] layouts, int i, Event event, Paint paint, Rect r) {
    if (i < 0 || i >= layouts.length) {
        return null;
    }

    StaticLayout layout = layouts[i];
    // Check if we have already initialized the StaticLayout and that
    // the width hasn't changed (due to vertical resizing which causes
    // re-layout of events at min height)
    if (layout == null || r.width() != layout.getWidth()) {
        SpannableStringBuilder bob = new SpannableStringBuilder();
        if (event.title != null) {
            // MAX - 1 since we add a space
            bob.append(drawTextSanitizer(event.title.toString(), MAX_EVENT_TEXT_LEN - 1));
            bob.setSpan(new StyleSpan(Typeface.BOLD), 0, bob.length(), 0);
            bob.append(' ');
        }
        if (event.location != null) {
            bob.append(drawTextSanitizer(event.location.toString(), MAX_EVENT_TEXT_LEN - bob.length()));
        }

        paint.setColor(mEventTextColor);

        // Leave a one pixel boundary on the left and right of the rectangle for the event
        layout = new StaticLayout(bob, 0, bob.length(), new TextPaint(paint), r.width(), Alignment.ALIGN_NORMAL,
                1.0f, 0.0f, true, null, r.width());

        layouts[i] = layout;
    }
    layout.getPaint().setAlpha(mEventsAlpha);
    return layout;
}

From source file:com.juick.android.JuickMessagesAdapter.java

private static void setStyleSpans(SpannableStringBuilder ssb, int ssbOffset, Object what, String styleChar) {
    String txt;/*  w ww. ja  va 2  s . co  m*/
    txt = ssb.subSequence(ssbOffset, ssb.length()).toString();
    txt = " " + txt + " ";
    ssbOffset -= 1;
    //
    int scan = 0;
    int cnt = 0;
    while (cnt++ < 20) { // don't need bugs in production.
        int ix = txt.indexOf(styleChar, scan);
        if (ix < 0)
            break;
        if (" \n".indexOf(txt.charAt(ix - 1)) != -1) {
            int ix2 = txt.indexOf(styleChar, ix + 1);
            if (ix2 < 0)
                break;
            if (" \n".indexOf(txt.charAt(ix2 + 1)) == -1 // not ends with space
                    || txt.substring(ix, ix2).indexOf("\n") != -1) { // spans several lines
                scan = ix2; // not ok
                continue;
            } else {
                CharacterStyle span = null;
                CharacterStyle span2 = null;
                // found needed stuff
                if (what instanceof Integer && (((Integer) what) == Typeface.BOLD)) {
                    span = new StyleSpan(Typeface.BOLD);
                    if (helvNueFonts) {
                        span2 = new CustomTypefaceSpan("", JuickAdvancedApplication.helvNueBold);
                    }
                }
                if (what instanceof Integer && (((Integer) what) == Typeface.ITALIC)) {
                    span = new StyleSpan(Typeface.ITALIC);
                }
                if (what == UnderlineSpan.class) {
                    span = new UnderlineSpan();
                }
                if (span != null && ix2 - ix > 1) {
                    ssb.delete(ssbOffset + ix, ssbOffset + ix + 1); // delete styling char
                    txt = stringDelete(txt, ix, ix + 1);
                    ix2--; // moves, too
                    ssb.delete(ssbOffset + ix2, ssbOffset + ix2 + 1); // second char deleted
                    txt = stringDelete(txt, ix2, ix2 + 1);
                    ssb.setSpan(span, ssbOffset + ix, ssbOffset + ix2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    if (span2 != null) {
                        ssb.setSpan(span2, ssbOffset + ix, ssbOffset + ix2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }
                }
                scan = ix2;
            }
        }
    }
}

From source file:com.juick.android.TagsFragment.java

private void reloadTags(final View view) {
    final View selectedContainer = myView.findViewById(R.id.selected_container);
    final View progressAll = myView.findViewById(R.id.progress_all);
    Thread thr = new Thread(new Runnable() {

        public void run() {
            Bundle args = getArguments();
            MicroBlog microBlog;/*w ww. ja  v  a  2 s .  c om*/
            JSONArray json = null;
            final int tagsUID = showMine ? uid : 0;
            if (PointMessageID.CODE.equals(args.getString("microblog"))) {
                microBlog = MainActivity.microBlogs.get(PointMessageID.CODE);
                json = ((PointMicroBlog) microBlog).getUserTags(view, uidS);
            } else {
                microBlog = MainActivity.microBlogs.get(JuickMessageID.CODE);
                json = ((JuickMicroBlog) microBlog).getUserTags(view, tagsUID);
            }
            if (isAdded()) {
                final SpannableStringBuilder tagsSSB = new SpannableStringBuilder();
                if (json != null) {
                    try {
                        int cnt = json.length();
                        ArrayList<TagSort> sortables = new ArrayList<TagSort>();
                        for (int i = 0; i < cnt; i++) {
                            final String tagg = json.getJSONObject(i).getString("tag");
                            final int messages = json.getJSONObject(i).getInt("messages");
                            sortables.add(new TagSort(tagg, messages));
                        }
                        Collections.sort(sortables);
                        HashMap<String, Double> scales = new HashMap<String, Double>();
                        for (int sz = 0, sortablesSize = sortables.size(); sz < sortablesSize; sz++) {
                            TagSort sortable = sortables.get(sz);
                            if (sz < 10) {
                                scales.put(sortable.tag, 2.0);
                            } else if (sz < 20) {
                                scales.put(sortable.tag, 1.5);
                            }
                        }
                        int start = 0;
                        if (microBlog instanceof JuickMicroBlog
                                && getArguments().containsKey("add_system_tags")) {
                            start = -4;
                        }
                        for (int i = start; i < cnt; i++) {
                            final String tagg;
                            switch (i) {
                            case -4:
                                tagg = "public";
                                break;
                            case -3:
                                tagg = "friends";
                                break;
                            case -2:
                                tagg = "notwitter";
                                break;
                            case -1:
                                tagg = "readonly";
                                break;
                            default:
                                tagg = json.getJSONObject(i).getString("tag");
                                break;

                            }
                            int index = tagsSSB.length();
                            tagsSSB.append("*" + tagg);
                            tagsSSB.setSpan(new URLSpan(tagg) {
                                @Override
                                public void onClick(View widget) {
                                    onTagClick(tagg, tagsUID);
                                }
                            }, index, tagsSSB.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            Double scale = scales.get(tagg);
                            if (scale != null) {
                                tagsSSB.setSpan(new RelativeSizeSpan((float) scale.doubleValue()), index,
                                        tagsSSB.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            }
                            tagOffsets.put(tagg, new TagOffsets(index, tagsSSB.length()));
                            tagsSSB.append(" ");

                        }
                    } catch (Exception ex) {
                        tagsSSB.append("Error: " + ex.toString());
                    }
                }
                if (getActivity() != null) {
                    // maybe already closed?
                    getActivity().runOnUiThread(new Runnable() {

                        public void run() {
                            TextView tv = (TextView) myView.findViewById(R.id.tags);
                            progressAll.setVisibility(View.GONE);
                            if (multi)
                                selectedContainer.setVisibility(View.VISIBLE);
                            tv.setText(tagsSSB, TextView.BufferType.SPANNABLE);
                            tv.setMovementMethod(LinkMovementMethod.getInstance());
                            MainActivity.restyleChildrenOrWidget(view);
                            final TextView selected = (TextView) myView.findViewById(R.id.selected);
                            selected.setVisibility(View.VISIBLE);
                        }
                    });
                }
            }
        }
    });
    thr.start();
}

From source file:org.kontalk.ui.ComposeMessageFragment.java

private void showIdentityDialog(boolean informationOnly, int titleId) {
    String fingerprint;/*from ww  w  .j  a  v  a 2s  .  c  om*/
    String uid;

    PGPPublicKeyRing publicKey = UsersProvider.getPublicKey(getActivity(), mUserJID, false);
    if (publicKey != null) {
        PGPPublicKey pk = PGP.getMasterKey(publicKey);
        fingerprint = PGP.formatFingerprint(PGP.getFingerprint(pk));
        uid = PGP.getUserId(pk, null); // TODO server!!!
    } else {
        // FIXME using another string
        fingerprint = uid = getString(R.string.peer_unknown);
    }

    SpannableStringBuilder text = new SpannableStringBuilder();
    text.append(getString(R.string.text_invitation1)).append('\n');

    Contact c = mConversation.getContact();
    if (c != null) {
        text.append(c.getName()).append(" <").append(c.getNumber()).append('>');
    } else {
        int start = text.length() - 1;
        text.append(uid);
        text.setSpan(MessageUtils.STYLE_BOLD, start, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    text.append('\n').append(getString(R.string.text_invitation2)).append('\n');

    int start = text.length() - 1;
    text.append(fingerprint);
    text.setSpan(MessageUtils.STYLE_BOLD, start, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    AlertDialogWrapper.Builder builder = new AlertDialogWrapper.Builder(getActivity()).setMessage(text);

    if (informationOnly) {
        builder.setTitle(titleId);
    } else {
        DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // hide warning bar
                hideWarning();

                switch (which) {
                case DialogInterface.BUTTON_POSITIVE:
                    // trust new key
                    trustKeyChange();
                    break;
                case DialogInterface.BUTTON_NEGATIVE:
                    // block user immediately
                    setPrivacy(PRIVACY_BLOCK);
                    break;
                }
            }
        };
        builder.setTitle(titleId).setPositiveButton(R.string.button_accept, listener)
                .setNegativeButton(R.string.button_block, listener);
    }

    builder.show();
}

From source file:com.aujur.ebookreader.activity.ReadingFragment.java

private void displayPageNumber(int pageNumber) {

    String pageString;//from   w w  w.  ja va 2 s  .c o m

    if (!config.isScrollingEnabled() && pageNumber > 0) {
        pageString = Integer.toString(pageNumber) + "\n";
    } else {
        pageString = "\n";
    }

    SpannableStringBuilder builder = new SpannableStringBuilder(pageString);
    builder.setSpan(new CenterSpan(), 0, builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    pageNumberView.setTextColor(config.getTextColor());
    pageNumberView.setTextSize(config.getTextSize());

    pageNumberView.setTypeface(config.getDefaultFontFamily().getDefaultTypeface());

    pageNumberView.setText(builder);
    pageNumberView.invalidate();
}

From source file:de.vanita5.twittnuker.util.Utils.java

public static CharSequence getKeywordHighlightedText(final CharSequence orig, final CharacterStyle style,
        final String... keywords) {
    if (keywords == null || keywords.length == 0 || orig == null)
        return orig;
    final SpannableStringBuilder sb = SpannableStringBuilder.valueOf(orig);
    final StringBuilder patternBuilder = new StringBuilder();
    for (int i = 0, j = keywords.length; i < j; i++) {
        if (i != 0) {
            patternBuilder.append('|');
        }/*from w ww. j  a  v  a  2s  .  c om*/
        patternBuilder.append(Pattern.quote(keywords[i]));
    }
    final Matcher m = Pattern.compile(patternBuilder.toString(), Pattern.CASE_INSENSITIVE).matcher(orig);
    while (m.find()) {
        sb.setSpan(style, m.start(), m.end(), SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE);
    }
    return sb;
}

From source file:com.vuze.android.remote.spanbubbles.SpanTags.java

public void setTagBubbles(final SpannableStringBuilder ss, String text, String token) {
    if (ss.length() > 0) {
        // hack to ensure descent is always added by TextView
        ss.append("\u200B");
    }/*ww w . j  a  va 2s  .  co m*/

    if (tvTags == null) {
        Log.e(TAG, "no tvTags");
        return;
    }

    TextPaint p = tvTags.getPaint();

    // Start and end refer to the points where the span will apply
    int tokenLen = token.length();
    int base = 0;

    if (showIcon && tagDrawables == null) {
        createDrawTagables();
    }

    while (true) {
        int start = text.indexOf(token, base);
        int end = text.indexOf(token, start + tokenLen);

        if (start < 0 || end < 0) {
            break;
        }

        base = end + tokenLen;

        final int fSpanStart = start;
        final int fSpanEnd = end + tokenLen;

        String id = text.substring(start + tokenLen, end);

        Map mapTag = null;
        try {
            long tagUID = Long.parseLong(id);
            mapTag = sessionInfo.getTag(tagUID);
        } catch (Throwable ignore) {
        }

        final String word = MapUtils.getMapString(mapTag, "name", "" + id);
        final Map fMapTag = mapTag;

        final DrawableTag imgDrawable = new DrawableTag(context, p, word, showIcon ? tagDrawables : null,
                mapTag, drawCount) {

            @Override
            public boolean isTagPressed() {
                if (!AndroidUtils.usesNavigationControl()) {
                    return false;
                }
                int selectionEnd = tvTags.getSelectionEnd();
                if (selectionEnd < 0) {
                    return false;
                }
                int selectionStart = tvTags.getSelectionStart();
                return selectionStart == fSpanStart && selectionEnd == fSpanEnd;
            }

            @Override
            public int getTagState() {
                if (listener == null) {
                    return TAG_STATE_SELECTED;
                }
                return listener.getTagState(fMapTag, word);
            }
        };

        if (countFontRatio > 0) {
            imgDrawable.setCountFontRatio(countFontRatio);
        }

        imgDrawable.setBounds(0, 0, imgDrawable.getIntrinsicWidth(), imgDrawable.getIntrinsicHeight());
        //         Log.d(TAG, "State=" + Arrays.toString(imgDrawable.getState()));

        if (listener != null && showIcon) {
            int tagState = listener.getTagState(mapTag, word);
            int[] state = makeState(tagState, mapTag == null, false);
            imgDrawable.setState(state);
        }

        ImageSpan imageSpan = new ImageSpan(imgDrawable, DynamicDrawableSpan.ALIGN_BASELINE) {

            @Override
            public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
                int size = super.getSize(paint, text, start, end, fm);
                int width = -1;
                if (tvTags.getLayoutParams().width == ViewGroup.LayoutParams.WRAP_CONTENT) {
                    if (tvTags.getParent() instanceof ViewGroup) {
                        width = ((ViewGroup) tvTags.getParent()).getWidth();
                    }
                } else {
                    width = tvTags.getWidth();
                }
                if (width <= 0) {
                    return size;
                }
                return Math.min(size, width);
            }
        };

        ss.setSpan(imageSpan, start, end + tokenLen, 0);

        if (listener != null) {
            ClickableSpan clickSpan = new ClickableSpan() {

                @Override
                public void onClick(View widget) {
                    listener.tagClicked(fMapTag, word);

                    if (AndroidUtils.hasTouchScreen()) {
                        Selection.removeSelection((Spannable) tvTags.getText());
                    }
                    widget.invalidate();
                }
            };

            ss.setSpan(clickSpan, start, end + tokenLen, 0);
        }

    }
}

From source file:org.telegram.ui.Components.ChatActivityEnterView.java

public void setEditingMessageObject(MessageObject messageObject, boolean caption) {
    if (audioToSend != null || editingMessageObject == messageObject) {
        return;/*ww  w. ja  v a 2s.c  o m*/
    }
    if (editingMessageReqId != 0) {
        ConnectionsManager.getInstance().cancelRequest(editingMessageReqId, true);
        editingMessageReqId = 0;
    }
    editingMessageObject = messageObject;
    editingCaption = caption;
    if (editingMessageObject != null) {
        if (doneButtonAnimation != null) {
            doneButtonAnimation.cancel();
            doneButtonAnimation = null;
        }
        doneButtonContainer.setVisibility(View.VISIBLE);
        showEditDoneProgress(true, false);

        InputFilter[] inputFilters = new InputFilter[1];
        if (caption) {
            inputFilters[0] = new InputFilter.LengthFilter(200);
            if (editingMessageObject.caption != null) {
                setFieldText(Emoji.replaceEmoji(
                        new SpannableStringBuilder(editingMessageObject.caption.toString()),
                        messageEditText.getPaint().getFontMetricsInt(), AndroidUtilities.dp(20), false));
            } else {
                setFieldText("");
            }
        } else {
            inputFilters[0] = new InputFilter.LengthFilter(4096);
            if (editingMessageObject.messageText != null) {
                ArrayList<TLRPC.MessageEntity> entities = editingMessageObject.messageOwner.entities;//MessagesQuery.getEntities(message);
                MessagesQuery.sortEntities(entities);
                SpannableStringBuilder stringBuilder = new SpannableStringBuilder(
                        editingMessageObject.messageText);
                Object spansToRemove[] = stringBuilder.getSpans(0, stringBuilder.length(), Object.class);
                if (spansToRemove != null && spansToRemove.length > 0) {
                    for (int a = 0; a < spansToRemove.length; a++) {
                        stringBuilder.removeSpan(spansToRemove[a]);
                    }
                }
                if (entities != null) {
                    int addToOffset = 0;
                    try {
                        for (int a = 0; a < entities.size(); a++) {
                            TLRPC.MessageEntity entity = entities.get(a);
                            if (entity.offset + entity.length + addToOffset > stringBuilder.length()) {
                                continue;
                            }
                            if (entity instanceof TLRPC.TL_inputMessageEntityMentionName) {
                                if (entity.offset + entity.length + addToOffset < stringBuilder.length()
                                        && stringBuilder
                                                .charAt(entity.offset + entity.length + addToOffset) == ' ') {
                                    entity.length++;
                                }
                                stringBuilder.setSpan(new URLSpanUserMention(
                                        "" + ((TLRPC.TL_inputMessageEntityMentionName) entity).user_id.user_id,
                                        true), entity.offset + addToOffset,
                                        entity.offset + entity.length + addToOffset,
                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            } else if (entity instanceof TLRPC.TL_messageEntityCode) {
                                stringBuilder.insert(entity.offset + entity.length + addToOffset, "`");
                                stringBuilder.insert(entity.offset + addToOffset, "`");
                                addToOffset += 2;
                            } else if (entity instanceof TLRPC.TL_messageEntityPre) {
                                stringBuilder.insert(entity.offset + entity.length + addToOffset, "```");
                                stringBuilder.insert(entity.offset + addToOffset, "```");
                                addToOffset += 6;
                            } else if (entity instanceof TLRPC.TL_messageEntityBold) {
                                stringBuilder.setSpan(
                                        new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")),
                                        entity.offset + addToOffset,
                                        entity.offset + entity.length + addToOffset,
                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            } else if (entity instanceof TLRPC.TL_messageEntityItalic) {
                                stringBuilder.setSpan(
                                        new TypefaceSpan(AndroidUtilities.getTypeface("fonts/ritalic.ttf")),
                                        entity.offset + addToOffset,
                                        entity.offset + entity.length + addToOffset,
                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            }
                        }
                    } catch (Exception e) {
                        FileLog.e(e);
                    }
                }
                setFieldText(Emoji.replaceEmoji(stringBuilder, messageEditText.getPaint().getFontMetricsInt(),
                        AndroidUtilities.dp(20), false));
            } else {
                setFieldText("");
            }
        }
        messageEditText.setFilters(inputFilters);
        openKeyboard();
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) messageEditText.getLayoutParams();
        layoutParams.rightMargin = AndroidUtilities.dp(4);
        messageEditText.setLayoutParams(layoutParams);
        sendButton.setVisibility(GONE);
        cancelBotButton.setVisibility(GONE);
        audioVideoButtonContainer.setVisibility(GONE);
        attachLayout.setVisibility(GONE);
        sendButtonContainer.setVisibility(GONE);
    } else {
        doneButtonContainer.setVisibility(View.GONE);
        messageEditText.setFilters(new InputFilter[0]);
        delegate.onMessageEditEnd(false);
        audioVideoButtonContainer.setVisibility(VISIBLE);
        attachLayout.setVisibility(VISIBLE);
        sendButtonContainer.setVisibility(VISIBLE);
        attachLayout.setScaleX(1.0f);
        attachLayout.setAlpha(1.0f);
        sendButton.setScaleX(0.1f);
        sendButton.setScaleY(0.1f);
        sendButton.setAlpha(0.0f);
        cancelBotButton.setScaleX(0.1f);
        cancelBotButton.setScaleY(0.1f);
        cancelBotButton.setAlpha(0.0f);
        audioVideoButtonContainer.setScaleX(1.0f);
        audioVideoButtonContainer.setScaleY(1.0f);
        audioVideoButtonContainer.setAlpha(1.0f);
        sendButton.setVisibility(GONE);
        cancelBotButton.setVisibility(GONE);
        messageEditText.setText("");
        if (getVisibility() == VISIBLE) {
            delegate.onAttachButtonShow();
        }
        updateFieldRight(1);
    }
    updateFieldHint();
}

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

private void initSearchBar() {
    if (searchBarInitialized)
        return;/*from w ww.j a v a2  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;
}

From source file:org.tvbrowser.tvbrowser.TvBrowser.java

private void showChannelSelectionInternal(final String selection, final String title, final String help,
        final boolean delete) {
    String[] projection = {/* w w  w. j av a 2 s .  co  m*/
            TvBrowserContentProvider.CHANNEL_TABLE + "." + TvBrowserContentProvider.KEY_ID + " AS "
                    + TvBrowserContentProvider.KEY_ID,
            TvBrowserContentProvider.GROUP_KEY_DATA_SERVICE_ID, TvBrowserContentProvider.CHANNEL_KEY_NAME,
            TvBrowserContentProvider.CHANNEL_KEY_SELECTION, TvBrowserContentProvider.CHANNEL_KEY_CATEGORY,
            TvBrowserContentProvider.CHANNEL_KEY_LOGO, TvBrowserContentProvider.CHANNEL_KEY_ALL_COUNTRIES };

    ContentResolver cr = getContentResolver();
    Cursor channels = cr.query(TvBrowserContentProvider.CONTENT_URI_CHANNELS_WITH_GROUP, projection, selection,
            null, TvBrowserContentProvider.CHANNEL_KEY_NAME);
    channels.moveToPosition(-1);

    // populate array list with all available channels
    final ArrayListWrapper channelSelectionList = new ArrayListWrapper();
    ArrayList<Country> countryList = new ArrayList<Country>();

    int channelIdColumn = channels.getColumnIndex(TvBrowserContentProvider.KEY_ID);
    int categoryColumn = channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_CATEGORY);
    int logoColumn = channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_LOGO);
    int dataServiceColumn = channels.getColumnIndex(TvBrowserContentProvider.GROUP_KEY_DATA_SERVICE_ID);
    int nameColumn = channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_NAME);
    int countyColumn = channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_ALL_COUNTRIES);
    int selectionColumn = channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_SELECTION);
    ;
    while (channels.moveToNext()) {
        int channelID = channels.getInt(channelIdColumn);
        int category = channels.getInt(categoryColumn);
        byte[] logo = channels.getBlob(logoColumn);
        String dataService = channels.getString(dataServiceColumn);
        String name = channels.getString(nameColumn);
        String countries = channels.getString(countyColumn);
        boolean isSelected = channels.getInt(selectionColumn) == 1 && !delete;

        if (countries.contains("$")) {
            String[] values = countries.split("\\$");

            for (String country : values) {
                Country test = new Country(new Locale(country, country));

                if (!countryList.contains(test) && test.mLocale.getDisplayCountry().trim().length() > 0) {
                    countryList.add(test);
                }
            }
        } else {
            Country test = new Country(new Locale(countries, countries));

            if (!countryList.contains(test) && test.mLocale.getDisplayCountry().trim().length() > 0) {
                countryList.add(test);
            }
        }

        Bitmap channelLogo = UiUtils.createBitmapFromByteArray(logo);

        if (channelLogo != null) {
            BitmapDrawable l = new BitmapDrawable(getResources(), channelLogo);

            ColorDrawable background = new ColorDrawable(SettingConstants.LOGO_BACKGROUND_COLOR);
            background.setBounds(0, 0, channelLogo.getWidth() + 2, channelLogo.getHeight() + 2);

            LayerDrawable logoDrawable = new LayerDrawable(new Drawable[] { background, l });
            logoDrawable.setBounds(background.getBounds());

            l.setBounds(2, 2, channelLogo.getWidth(), channelLogo.getHeight());

            channelLogo = UiUtils.drawableToBitmap(logoDrawable);
        }

        channelSelectionList.add(new ChannelSelection(channelID, name, category, countries, channelLogo,
                isSelected, SettingConstants.EPG_DONATE_KEY.equals(dataService)));
    }

    // sort countries for filtering
    Collections.sort(countryList, new Comparator<Country>() {
        @Override
        public int compare(Country lhs, Country rhs) {
            return lhs.toString().compareToIgnoreCase(rhs.toString());
        }
    });

    countryList.add(0, new Country(null));

    channels.close();

    // create filter for filtering of category and country
    final ChannelFilter filter = new ChannelFilter(SettingConstants.TV_CATEGORY, null);

    // create default logo for channels without logo
    final Bitmap defaultLogo = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);

    final Set<String> firstDeletedChannels = PrefUtils.getStringSetValue(R.string.PREF_FIRST_DELETED_CHANNELS,
            new HashSet<String>());
    final Set<String> keptDeletedChannels = PrefUtils.getStringSetValue(R.string.PREF_KEPT_DELETED_CHANNELS,
            new HashSet<String>());

    final int firstDeletedColor = getResources().getColor(R.color.pref_first_deleted_channels);
    final int keptDeletedColor = getResources().getColor(R.color.pref_kept_deleted_channels);

    // Custom array adapter for channel selection
    final ArrayAdapter<ChannelSelection> channelSelectionAdapter = new ArrayAdapter<ChannelSelection>(
            TvBrowser.this, R.layout.channel_row, channelSelectionList) {
        public View getView(int position, View convertView, ViewGroup parent) {
            ChannelSelection value = getItem(position);
            ViewHolder holder = null;

            if (convertView == null) {
                LayoutInflater mInflater = (LayoutInflater) getContext()
                        .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

                holder = new ViewHolder();

                convertView = mInflater.inflate(R.layout.channel_row, getParentViewGroup(), false);

                holder.mTextView = (TextView) convertView.findViewById(R.id.row_of_channel_text);
                holder.mCheckBox = (CheckBox) convertView.findViewById(R.id.row_of_channel_selection);
                holder.mLogo = (ImageView) convertView.findViewById(R.id.row_of_channel_icon);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            SpannableStringBuilder nameBuilder = new SpannableStringBuilder(value.toString());

            String channelID = String.valueOf(value.getChannelID());

            if (keptDeletedChannels.contains(channelID)) {
                nameBuilder.setSpan(new ForegroundColorSpan(keptDeletedColor), 0, value.toString().length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else if (firstDeletedChannels.contains(channelID)) {
                nameBuilder.setSpan(new ForegroundColorSpan(firstDeletedColor), 0, value.toString().length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

            if (value.isEpgDonateChannel()) {
                nameBuilder.append("\n(EPGdonate)");
                nameBuilder.setSpan(new RelativeSizeSpan(0.65f), value.toString().length(),
                        nameBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

            holder.mTextView.setText(nameBuilder);
            holder.mCheckBox.setChecked(value.isSelected());

            Bitmap logo = value.getLogo();

            if (logo != null) {
                holder.mLogo.setImageBitmap(logo);
            } else {
                holder.mLogo.setImageBitmap(defaultLogo);
            }

            return convertView;
        }
    };

    // inflate channel selection view
    View channelSelectionView = getLayoutInflater().inflate(R.layout.dialog_channel_selection_list,
            getParentViewGroup(), false);
    channelSelectionView.findViewById(R.id.channel_selection_selection_buttons).setVisibility(View.GONE);
    channelSelectionView.findViewById(R.id.channel_selection_input_id_name).setVisibility(View.GONE);

    TextView infoView = (TextView) channelSelectionView.findViewById(R.id.channel_selection_label_id_name);

    if (help != null) {
        infoView.setText(help);
        infoView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
                getResources().getDimension(R.dimen.epg_donate_info_font_size));
    } else {
        infoView.setVisibility(View.GONE);
    }

    // get spinner for country filtering and create array adapter with all available countries
    Spinner country = (Spinner) channelSelectionView.findViewById(R.id.channel_country_value);

    final ArrayAdapter<Country> countryListAdapter = new ArrayAdapter<Country>(this,
            android.R.layout.simple_spinner_item, countryList);
    countryListAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    country.setAdapter(countryListAdapter);

    // add item selection listener to react of user setting filter for country
    country.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Country country = countryListAdapter.getItem(position);

            filter.mCountry = country.getCountry();
            channelSelectionList.setFilter(filter);
            channelSelectionAdapter.notifyDataSetChanged();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    // get spinner for category selection and add listener to react to user category selection
    Spinner category = (Spinner) channelSelectionView.findViewById(R.id.channel_category_value);
    category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            switch (position) {
            case 1:
                filter.mCategory = SettingConstants.TV_CATEGORY;
                break;
            case 2:
                filter.mCategory = SettingConstants.RADIO_CATEGORY;
                break;
            case 3:
                filter.mCategory = SettingConstants.CINEMA_CATEGORY;
                break;

            default:
                filter.mCategory = SettingConstants.NO_CATEGORY;
                break;
            }

            channelSelectionList.setFilter(filter);
            channelSelectionAdapter.notifyDataSetChanged();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    if (delete) {
        channelSelectionView.findViewById(R.id.channel_country_label).setVisibility(View.GONE);
        channelSelectionView.findViewById(R.id.channel_category_label).setVisibility(View.GONE);

        country.setVisibility(View.GONE);
        category.setVisibility(View.GONE);
    }

    // get the list view of the layout and add adapter with available channels
    ListView list = (ListView) channelSelectionView.findViewById(R.id.channel_selection_list);
    list.setAdapter(channelSelectionAdapter);

    // add listener to react to user selection of channels
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            CheckBox check = (CheckBox) view.findViewById(R.id.row_of_channel_selection);

            if (check != null) {
                check.setChecked(!check.isChecked());
                channelSelectionAdapter.getItem(position).setSelected(check.isChecked());
            }
        }
    });

    // show dialog only if channels are available
    if (!channelSelectionList.isEmpty()) {
        AlertDialog.Builder builder = new AlertDialog.Builder(TvBrowser.this);

        if (title == null) {
            builder.setTitle(R.string.select_channels);
        } else {
            builder.setTitle(title);
        }

        builder.setView(channelSelectionView);

        builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                boolean somethingSelected = false;
                boolean somethingChanged = false;

                Iterator<ChannelSelection> it = channelSelectionList.superIterator();

                StringBuilder deleteWhere = new StringBuilder();
                HashSet<String> keep = new HashSet<String>();

                while (it.hasNext()) {
                    ChannelSelection sel = it.next();

                    if (sel.isSelected() && !sel.wasSelected()) {
                        somethingChanged = somethingSelected = true;

                        if (delete) {
                            if (deleteWhere.length() > 0) {
                                deleteWhere.append(", ");
                            }

                            deleteWhere.append(sel.getChannelID());
                        } else {
                            ContentValues values = new ContentValues();

                            values.put(TvBrowserContentProvider.CHANNEL_KEY_SELECTION, 1);

                            getContentResolver().update(
                                    ContentUris.withAppendedId(TvBrowserContentProvider.CONTENT_URI_CHANNELS,
                                            sel.getChannelID()),
                                    values, null, null);
                        }
                    } else if (!sel.isSelected() && sel.wasSelected()) {
                        somethingChanged = true;

                        ContentValues values = new ContentValues();

                        values.put(TvBrowserContentProvider.CHANNEL_KEY_SELECTION, 0);

                        getContentResolver().update(
                                ContentUris.withAppendedId(TvBrowserContentProvider.CONTENT_URI_CHANNELS,
                                        sel.getChannelID()),
                                values, null, null);

                        getContentResolver().delete(TvBrowserContentProvider.CONTENT_URI_DATA_VERSION,
                                TvBrowserContentProvider.CHANNEL_KEY_CHANNEL_ID + "=" + sel.getChannelID(),
                                null);
                        getContentResolver().delete(TvBrowserContentProvider.CONTENT_URI_DATA,
                                TvBrowserContentProvider.CHANNEL_KEY_CHANNEL_ID + "=" + sel.getChannelID(),
                                null);
                    } else if (delete && !sel.isSelected()) {
                        keep.add(String.valueOf(sel.getChannelID()));
                    }
                }

                if (delete) {
                    if (deleteWhere.length() > 0) {
                        deleteWhere.insert(0, TvBrowserContentProvider.KEY_ID + " IN ( ");
                        deleteWhere.append(" ) ");

                        Log.d("info2", "DELETE WHERE FOR REMOVED CHANNELS " + deleteWhere.toString());

                        int count = getContentResolver().delete(TvBrowserContentProvider.CONTENT_URI_CHANNELS,
                                deleteWhere.toString(), null);

                        Log.d("info2", "REMOVED CHANNELS COUNT " + count);
                    }

                    Editor edit = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this).edit();
                    edit.putStringSet(getString(R.string.PREF_KEPT_DELETED_CHANNELS), keep);
                    edit.commit();
                }

                // if something was changed we need to update channel list bar in program list and the complete program table
                if (somethingChanged) {
                    SettingConstants.initializeLogoMap(TvBrowser.this, true);
                    updateProgramListChannelBar();
                }

                // if something was selected we need to download new data
                if (somethingSelected && !delete) {
                    checkTermsAccepted();
                }
            }
        });

        builder.setNegativeButton(android.R.string.cancel, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (delete) {
                    HashSet<String> keep = new HashSet<String>();
                    Iterator<ChannelSelection> it = channelSelectionList.superIterator();

                    while (it.hasNext()) {
                        ChannelSelection sel = it.next();

                        keep.add(String.valueOf(sel.getChannelID()));
                    }

                    Editor edit = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this).edit();
                    edit.putStringSet(getString(R.string.PREF_KEPT_DELETED_CHANNELS), keep);
                    edit.commit();
                }
            }
        });

        builder.show();
    }

    selectingChannels = false;
}