Example usage for android.text Spanned SPAN_EXCLUSIVE_EXCLUSIVE

List of usage examples for android.text Spanned SPAN_EXCLUSIVE_EXCLUSIVE

Introduction

In this page you can find the example usage for android.text Spanned SPAN_EXCLUSIVE_EXCLUSIVE.

Prototype

int SPAN_EXCLUSIVE_EXCLUSIVE

To view the source code for android.text Spanned SPAN_EXCLUSIVE_EXCLUSIVE.

Click Source Link

Document

Spans of type SPAN_EXCLUSIVE_EXCLUSIVE do not expand to include text inserted at either their starting or ending point.

Usage

From source file:us.phyxsi.gameshelf.ui.HomeActivity.java

private void setNoResultsEmptyTextVisibility(int visibility) {
    if (visibility == View.VISIBLE) {
        if (noResultsEmptyText == null) {
            // create the no results empty text
            ViewStub stub = (ViewStub) findViewById(R.id.stub_no_results);
            noResultsEmptyText = (TextView) stub.inflate();
            String emptyText = getString(R.string.no_results_found);
            int addPlaceholderStart = emptyText.indexOf('\u08B4');
            int altMethodStart = addPlaceholderStart + 3;
            SpannableStringBuilder ssb = new SpannableStringBuilder(emptyText);
            // show an image of the add icon
            ssb.setSpan(new ImageSpan(this, R.drawable.ic_add_small, ImageSpan.ALIGN_BASELINE),
                    addPlaceholderStart, addPlaceholderStart + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            // make the alt method (swipe from right) less prominent and italic
            ssb.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.text_secondary_light)),
                    altMethodStart, emptyText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            ssb.setSpan(new StyleSpan(Typeface.ITALIC), altMethodStart, emptyText.length(),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            noResultsEmptyText.setText(ssb);
        }//  w ww . ja v a  2s . c o m

        noResultsEmptyText.setVisibility(visibility);
    } else if (noResultsEmptyText != null) {
        noResultsEmptyText.setVisibility(visibility);
    }
}

From source file:com.silentcircle.contacts.vcard.ManageVCardActivity.java

private Dialog getVCardFileSelectDialog(boolean multipleSelect) {
    final int size = mAllVCardFileList.size();
    final VCardSelectedListener listener = new VCardSelectedListener(multipleSelect);

    final AlertDialog.Builder builder = new AlertDialog.Builder(this)
            .setTitle(R.string.select_vcard_title_remove).setPositiveButton(android.R.string.ok, listener)
            .setOnCancelListener(mCancelListener).setNegativeButton(android.R.string.cancel, mCancelListener);

    CharSequence[] items = new CharSequence[size];
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    for (int i = 0; i < size; i++) {
        VCardFile vcardFile = mAllVCardFileList.get(i);
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
        stringBuilder.append(vcardFile.getName());
        stringBuilder.append('\n');
        int indexToBeSpanned = stringBuilder.length();
        // Smaller date text looks better, since each file name becomes easier to read.
        // The value set to RelativeSizeSpan is arbitrary. You can change it to any other
        // value (but the value bigger than 1.0f would not make nice appearance :)
        stringBuilder.append("(" + dateFormat.format(new Date(vcardFile.getLastModified())) + ")");
        stringBuilder.setSpan(new RelativeSizeSpan(0.7f), indexToBeSpanned, stringBuilder.length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        items[i] = stringBuilder;//from ww w  .  j a  va2  s  .c  om
    }
    if (multipleSelect) {
        builder.setMultiChoiceItems(items, (boolean[]) null, listener);
    } else {
        builder.setSingleChoiceItems(items, 0, listener);
    }
    return builder.create();
}

From source file:de.ub0r.android.lib.DonationHelper.java

/**
 * Show "donate" dialog.// w w  w. j  ava  2 s  . c  o  m
 * 
 * @param context
 *            {@link Context}
 * @param title
 *            title
 * @param btnDonate
 *            button text for donate
 * @param btnNoads
 *            button text for "i did a donation"
 * @param messages
 *            messages for dialog body
 */
public static void showDonationDialog(final Activity context, final String title, final String btnDonate,
        final String btnNoads, final String[] messages) {
    final Intent marketIntent = Market.getInstallAppIntent(context, DONATOR_PACKAGE, null);

    String btnTitle = String.format(btnDonate, "Play Store");

    SpannableStringBuilder sb = new SpannableStringBuilder();
    for (String m : messages) {
        sb.append(m);
        sb.append("\n");
    }
    sb.delete(sb.length() - 1, sb.length());
    sb.setSpan(new RelativeSizeSpan(0.75f), 0, sb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    AlertDialog.Builder b = new AlertDialog.Builder(context);
    b.setTitle(title);
    b.setMessage(sb);
    b.setCancelable(true);
    b.setPositiveButton(btnTitle, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(final DialogInterface dialog, final int which) {
            try {
                context.startActivity(marketIntent);
            } catch (ActivityNotFoundException e) {
                Log.e(TAG, "activity not found", e);
                Toast.makeText(context, "activity not found", Toast.LENGTH_LONG).show();
            }
        }
    });
    b.setNeutralButton(btnNoads, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(final DialogInterface dialog, final int which) {
            try {
                context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(
                        "http://code.google.com/p/ub0rapps/downloads/list?" + "can=3&q=Product%3DDonator")));
            } catch (ActivityNotFoundException e) {
                Log.e(TAG, "activity not found", e);
                Toast.makeText(context, "activity not found", Toast.LENGTH_LONG).show();
            }
        }
    });
    b.show();
}

From source file:org.mariotaku.twidere.view.holder.ActivityTitleSummaryViewHolder.java

public void displayActivity(ParcelableActivity activity, boolean byFriends) {
    final Context context = adapter.getContext();
    final Resources resources = adapter.getContext().getResources();
    switch (activity.action) {
    case Activity.ACTION_FOLLOW: {
        activityTypeView.setImageResource(R.drawable.ic_activity_action_follow);
        activityTypeView.setColorFilter(ContextCompat.getColor(context, R.color.highlight_follow),
                Mode.SRC_ATOP);/*from  w  w w  .j  a va  2  s  .co m*/
        if (byFriends) {
            titleView.setText(getTitleStringByFriends(R.string.activity_by_friends_follow,
                    R.string.activity_by_friends_follow_multi, activity.sources, activity.target_users));
        } else {
            titleView.setText(getTitleStringAboutMe(R.string.activity_about_me_follow,
                    R.string.activity_about_me_follow_multi, activity.sources));
        }
        displayUserProfileImages(activity.sources);
        summaryView.setVisibility(View.GONE);
        break;
    }
    case Activity.ACTION_FAVORITE: {
        if (adapter.shouldUseStarsForLikes()) {
            activityTypeView.setImageResource(R.drawable.ic_activity_action_favorite);
            activityTypeView.setColorFilter(ContextCompat.getColor(context, R.color.highlight_favorite),
                    Mode.SRC_ATOP);

            if (byFriends) {
                titleView.setText(getTitleStringByFriends(R.string.activity_by_friends_favorite,
                        R.string.activity_by_friends_favorite_multi, activity.sources,
                        activity.target_statuses));
            } else {
                titleView.setText(getTitleStringAboutMe(R.string.activity_about_me_favorite,
                        R.string.activity_about_me_favorite_multi, activity.sources));
            }
        } else {
            activityTypeView.setImageResource(R.drawable.ic_activity_action_like);
            activityTypeView.setColorFilter(ContextCompat.getColor(context, R.color.highlight_like),
                    Mode.SRC_ATOP);

            if (byFriends) {
                titleView.setText(getTitleStringByFriends(R.string.activity_by_friends_like,
                        R.string.activity_by_friends_like_multi, activity.sources, activity.target_statuses));
            } else {
                titleView.setText(getTitleStringAboutMe(R.string.activity_about_me_like,
                        R.string.activity_about_me_like_multi, activity.sources));
            }
        }
        displayUserProfileImages(activity.sources);
        summaryView.setText(activity.target_statuses[0].text_unescaped);
        summaryView.setVisibility(View.VISIBLE);
        break;
    }
    case Activity.ACTION_RETWEET: {
        activityTypeView.setImageResource(R.drawable.ic_activity_action_retweet);
        activityTypeView.setColorFilter(ContextCompat.getColor(context, R.color.highlight_retweet),
                Mode.SRC_ATOP);
        if (byFriends) {
            titleView.setText(getTitleStringByFriends(R.string.activity_by_friends_retweet,
                    R.string.activity_by_friends_retweet_multi, activity.sources, activity.target_statuses));
        } else
            titleView.setText(getTitleStringAboutMe(R.string.activity_about_me_retweet,
                    R.string.activity_about_me_retweet_multi, activity.sources));
        displayUserProfileImages(activity.sources);
        summaryView.setText(activity.target_statuses[0].text_unescaped);
        summaryView.setVisibility(View.VISIBLE);
        break;
    }
    case Activity.ACTION_FAVORITED_RETWEET: {
        if (byFriends) {
            showNotSupported();
            return;
        }
        if (adapter.shouldUseStarsForLikes()) {
            activityTypeView.setImageResource(R.drawable.ic_activity_action_favorite);
            activityTypeView.setColorFilter(ContextCompat.getColor(context, R.color.highlight_favorite),
                    Mode.SRC_ATOP);
            titleView.setText(getTitleStringAboutMe(R.string.activity_about_me_favorited_retweet,
                    R.string.activity_about_me_favorited_retweet_multi, activity.sources));
        } else {
            activityTypeView.setImageResource(R.drawable.ic_activity_action_like);
            activityTypeView.setColorFilter(ContextCompat.getColor(context, R.color.highlight_like),
                    Mode.SRC_ATOP);
            titleView.setText(getTitleStringAboutMe(R.string.activity_about_me_liked_retweet,
                    R.string.activity_about_me_liked_retweet_multi, activity.sources));
        }
        displayUserProfileImages(activity.sources);
        summaryView.setText(activity.target_statuses[0].text_unescaped);
        summaryView.setVisibility(View.VISIBLE);
        break;
    }
    case Activity.ACTION_RETWEETED_RETWEET: {
        if (byFriends) {
            showNotSupported();
            return;
        }
        activityTypeView.setImageResource(R.drawable.ic_activity_action_retweet);
        activityTypeView.setColorFilter(ContextCompat.getColor(context, R.color.highlight_retweet),
                Mode.SRC_ATOP);
        titleView.setText(getTitleStringAboutMe(R.string.activity_about_me_retweeted_retweet,
                R.string.activity_about_me_retweeted_retweet_multi, activity.sources));
        displayUserProfileImages(activity.sources);
        summaryView.setText(activity.target_statuses[0].text_unescaped);
        summaryView.setVisibility(View.VISIBLE);
        break;
    }
    case Activity.ACTION_RETWEETED_MENTION: {
        if (byFriends) {
            showNotSupported();
            return;
        }
        activityTypeView.setImageResource(R.drawable.ic_activity_action_retweet);
        activityTypeView.setColorFilter(ContextCompat.getColor(context, R.color.highlight_retweet),
                Mode.SRC_ATOP);
        titleView.setText(getTitleStringAboutMe(R.string.activity_about_me_retweeted_mention,
                R.string.activity_about_me_retweeted_mention_multi, activity.sources));
        displayUserProfileImages(activity.sources);
        summaryView.setText(activity.target_statuses[0].text_unescaped);
        summaryView.setVisibility(View.VISIBLE);
        break;
    }
    case Activity.ACTION_FAVORITED_MENTION: {
        if (byFriends) {
            showNotSupported();
            return;
        }
        if (adapter.shouldUseStarsForLikes()) {
            activityTypeView.setImageResource(R.drawable.ic_activity_action_favorite);
            activityTypeView.setColorFilter(ContextCompat.getColor(context, R.color.highlight_favorite),
                    Mode.SRC_ATOP);
            titleView.setText(getTitleStringAboutMe(R.string.activity_about_me_favorited_mention,
                    R.string.activity_about_me_favorited_mention_multi, activity.sources));
        } else {
            activityTypeView.setImageResource(R.drawable.ic_activity_action_like);
            activityTypeView.setColorFilter(ContextCompat.getColor(context, R.color.highlight_like),
                    Mode.SRC_ATOP);
            titleView.setText(getTitleStringAboutMe(R.string.activity_about_me_liked_mention,
                    R.string.activity_about_me_liked_mention_multi, activity.sources));
        }
        displayUserProfileImages(activity.sources);
        summaryView.setText(activity.target_statuses[0].text_unescaped);
        summaryView.setVisibility(View.VISIBLE);
        break;
    }
    case Activity.ACTION_LIST_CREATED: {
        if (!byFriends) {
            showNotSupported();
            return;
        }
        activityTypeView.setImageResource(R.drawable.ic_activity_action_list_added);
        activityTypeView.setColorFilter(activityTypeView.getDefaultColor(), Mode.SRC_ATOP);
        titleView.setText(getTitleStringByFriends(R.string.activity_by_friends_list_created,
                R.string.activity_by_friends_list_created_multi, activity.sources,
                activity.target_object_user_lists));
        displayUserProfileImages(activity.sources);
        boolean firstLine = true;
        summaryView.setText("");
        for (ParcelableUserList item : activity.target_object_user_lists) {
            if (!firstLine) {
                summaryView.append("\n");
            }
            summaryView.append(item.description);
            firstLine = false;
        }
        summaryView.setVisibility(View.VISIBLE);
        break;
    }
    case Activity.ACTION_LIST_MEMBER_ADDED: {
        if (byFriends) {
            showNotSupported();
            return;
        }
        activityTypeView.setImageResource(R.drawable.ic_activity_action_list_added);
        activityTypeView.setColorFilter(activityTypeView.getDefaultColor(), Mode.SRC_ATOP);
        if (activity.sources.length == 1 && activity.target_object_user_lists != null
                && activity.target_object_user_lists.length == 1) {
            final UserColorNameManager manager = adapter.getUserColorNameManager();
            final SpannableString firstDisplayName = new SpannableString(
                    manager.getDisplayName(activity.sources[0], adapter.isNameFirst(), false));
            final SpannableString listName = new SpannableString(activity.target_object_user_lists[0].name);
            firstDisplayName.setSpan(new StyleSpan(Typeface.BOLD), 0, firstDisplayName.length(),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            listName.setSpan(new StyleSpan(Typeface.BOLD), 0, listName.length(),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            final String format = context.getString(R.string.activity_about_me_list_member_added_with_name);
            final Configuration configuration = resources.getConfiguration();
            titleView.setText(SpanFormatter.format(configuration.locale, format, firstDisplayName, listName));
        } else {
            titleView.setText(getTitleStringAboutMe(R.string.activity_about_me_list_member_added,
                    R.string.activity_about_me_list_member_added_multi, activity.sources));
        }
        displayUserProfileImages(activity.sources);
        summaryView.setVisibility(View.GONE);
        break;
    }
    }
}

From source file:org.bobstuff.bobball.ActivityStateEnum.java

private void showWonScreen() {
    activityState = ActivityStateEnum.GAMEWON;

    Statistics.saveHighestLevel(numPlayers, gameManager.getLevel() + 1);
    levelSeries++;// w  w w.  j a  v a2s  .  c om
    Statistics.saveLongestSeries(levelSeries);

    GameState gs = gameManager.getCurrGameState();
    Grid currGrid = gs.getGrid();

    SpannableStringBuilder percentageCleared = new SpannableStringBuilder();

    String percentageString = currGrid.getPercentCompleteFloat(1) + "%";

    String totalPercentageString = getString(R.string.percentageCleared, percentageString);

    int player1Color = gs.getPlayer(1).getColor();

    SpannableString percentage = new SpannableString(totalPercentageString);
    int percentageStart = totalPercentageString.length() - percentageString.length();
    int percentageEnd = totalPercentageString.length();

    percentage.setSpan(new ForegroundColorSpan(player1Color), percentageStart, percentageEnd,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    percentageCleared.append(percentage);

    messageView.setText(getString(R.string.levelCompleted, gameManager.getLevel()));
    button.setText(R.string.nextLevel);
    retryButton.setVisibility(View.GONE);
    button.setVisibility(View.VISIBLE);
    backToLevelSelectButton.setVisibility(View.GONE);
    this.percentageCleared.setText(percentageCleared);
    this.percentageCleared.setVisibility(View.VISIBLE);

    if (numPlayers > 1) {
        totalPercentageCleared
                .setText(getString(R.string.totalPercentageCleared, currGrid.getPercentCompleteFloat() + "%"));
        totalPercentageCleared.setVisibility(View.VISIBLE);
    }

    bonusPoints.setText(getString(R.string.bonusPoints, gameManager.getBonusPoints(gs, gs.getPlayer(1))));
    bonusPoints.setVisibility(View.VISIBLE);

    setMessageViewsVisible(true);
}

From source file:io.plaidapp.ui.widget.CollapsingTitleLayout.java

private void setScrollOffsetMultiLine() {
    // loop over each line and check/set an appropriate alpha for the current scroll offset
    for (int i = 1; i < lineCount; i++) {
        Line line = lines[i];/*ww  w .  ja  va2 s .  co m*/
        float lineAlpha = 1f;
        if (scrollOffset >= line.zeroAlphaScrollOffset) {
            lineAlpha = 0f;
        } else if (scrollOffset <= line.fullAlphaScrollOffset) {
            lineAlpha = 1f;
        } else if (scrollOffset > line.fullAlphaScrollOffset && scrollOffset < line.zeroAlphaScrollOffset) {
            lineAlpha = 1f - (scrollOffset - line.zeroAlphaScrollOffset)
                    / (line.zeroAlphaScrollOffset - line.fullAlphaScrollOffset);
        }
        if (line.currentAlpha != lineAlpha) {
            displayText.removeSpan(line.span);
            line.span = new ForegroundColorSpan(ColorUtils.modifyAlpha(paint.getColor(), lineAlpha));
            displayText.setSpan(line.span, line.startIndex, line.endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            line.currentAlpha = lineAlpha;
        }
    }
}

From source file:com.amitupadhyay.aboutexample.ui.widget.CollapsingTitleLayout.java

private void setScrollOffsetMultiLine() {
    // loop over each line and check/set an appropriate alpha for the current scroll offset
    for (int i = 1; i < lineCount; i++) {
        Line line = lines[i];//from  w w  w  . java 2  s .c  o  m
        float lineAlpha = 1f;
        if (scrollOffset >= line.zeroAlphaScrollOffset) {
            lineAlpha = 0f;
        } else if (scrollOffset <= line.fullAlphaScrollOffset) {
            lineAlpha = 1f;
        } else if (scrollOffset > line.fullAlphaScrollOffset && scrollOffset < line.zeroAlphaScrollOffset) {
            lineAlpha = 1f - (scrollOffset - line.fullAlphaScrollOffset)
                    / (line.zeroAlphaScrollOffset - line.fullAlphaScrollOffset);
        }
        if (line.currentAlpha != lineAlpha) {
            // mutating a span does not re-draw, need to remove and re-set it
            displayText.removeSpan(line.span);
            line.span.setAlpha(lineAlpha);
            displayText.setSpan(line.span, line.startIndex, line.endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            line.currentAlpha = lineAlpha;
        }
    }
}

From source file:li.barter.activities.AbstractBarterLiActivity.java

/**
 * Sets the Action bar title, using the desired {@link Typeface} loaded from {@link
 * TypefaceCache}/*from w w  w  . j  a v  a  2 s . c o  m*/
 *
 * @param title The title to set for the Action Bar
 */

public final void setActionBarTitle(final String title) {

    final SpannableString s = new SpannableString(title);
    s.setSpan(new TypefacedSpan(this, TypefaceCache.SLAB_REGULAR), 0, s.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    // Update the action bar title with the TypefaceSpan instance
    final ActionBar actionBar = getSupportActionBar();
    actionBar.setTitle(s);
}

From source file:com.nearnotes.NoteEdit.java

/**
 * Populates the checkboxes on the side by analyzing the current text from
 * the body of the note./*from  www  .  ja  va  2s.  com*/
 * 
 * @param currentString
 *            the current body of the note.
 * 
 */
public ArrayList<NoteRow> populateBoxes(String currentString) {

    // Load ArrayList<String> mLines with the current bodytext seperated into seperate lines.
    mLines = Arrays.asList(currentString.split(System.getProperty("line.separator")));

    // row counter to determine what the current line number is for the for loop
    int row = 0;

    // realRow counter to determine what line of text in the actual display we are on
    // used to get the number of characters on each line
    int realRow = 0;
    int activeRow = 0;
    int finishedCount = 0;

    ArrayList<NoteRow> tempRealRow = new ArrayList<NoteRow>();
    for (String line : mLines) {
        NoteRow temp = new NoteRow(0, 1, row); // Create a note row object with rowType of 0 (invisible), lineSize of 1 and the current row number

        if (!line.isEmpty()) {
            activeRow++;
            temp.setType(1); // Set the NoteRow object to 1 (visible)

            // Determine how many lines the note takes up
            int internalCounter = 0;
            try {
                float lineLength = (float) line.length();
                for (int k = 0; (lineLength
                        / (getFloatLineEnd(realRow + k) - getFloatLineEnd(realRow - 1))) > 1; k++) {
                    internalCounter++;
                }
            } catch (NullPointerException e) {
                e.printStackTrace();
            }

            // Detemine if the note is supposed to be checked and set the NoteRow object to 2 (Checked)
            if (line.startsWith("[X]")) {
                finishedCount++;
                int spanstart = 0;
                StrikethroughSpan STRIKE_THROUGH_SPAN = new StrikethroughSpan();
                Spannable spannable = (Spannable) mBodyText.getText();
                // TableRow checkRow1 = (TableRow) View.inflate(getActivity(), R.layout.table_row, null);

                for (int j = 0; j < row; j++) {
                    spanstart += mLines.get(j).length() + 1;
                }

                Object spansToRemove[] = spannable.getSpans(spanstart, spanstart + mLines.get(row).length(),
                        Object.class);
                for (Object span : spansToRemove) {
                    if (span instanceof CharacterStyle)
                        spannable.removeSpan(span);
                }

                spannable.setSpan(STRIKE_THROUGH_SPAN, spanstart, spanstart + mLines.get(row).length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                temp.setType(2);
            }

            temp.setSize(1 + internalCounter); // Set the amount of rows the note takes up
            realRow = realRow + internalCounter; // Determine the real line on the display text we are on
        }

        tempRealRow.add(temp); // NoteRow object has been finalized - add to the ListArray<NoteRow>
        realRow++; // Increase the noteRow and the displayRow for the next line
        row++;
    }

    if (finishedCount == activeRow && finishedCount != 0) {

        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
        boolean useListPref = sharedPref.getBoolean("pref_key_use_checklist_default", false);
        String stringlistPref = sharedPref.getString("pref_key_checklist_listPref", "2");
        int listPref = Integer.parseInt(stringlistPref);

        ChecklistDialog newFragment = new ChecklistDialog();
        if (mRowId == null) {
            saveState();
        }
        Bundle args = new Bundle();
        args.putLong("_id", mRowId);
        args.putBoolean("useDefault", useListPref);
        args.putInt("listPref", listPref);
        newFragment.setArguments(args);
        if (listPref == 2 && useListPref) {
            return tempRealRow;
        }
        if (getFragmentManager().findFragmentByTag("MyDialog") == null) {
            newFragment.show(getFragmentManager(), "MyDialog");
        }

    }

    return tempRealRow;
}

From source file:com.keylesspalace.tusky.activity.MainActivity.java

private void setupSearchView() {
    searchView.attachNavigationDrawerToMenuButton(drawer.getDrawerLayout());

    searchView.setOnQueryChangeListener(new FloatingSearchView.OnQueryChangeListener() {
        @Override//www . j a v  a  2  s . com
        public void onSearchTextChanged(String oldQuery, String newQuery) {
            if (!oldQuery.equals("") && newQuery.equals("")) {
                searchView.clearSuggestions();
                return;
            }

            if (newQuery.length() < 3) {
                return;
            }

            searchView.showProgress();

            mastodonAPI.searchAccounts(newQuery, false, 5).enqueue(new Callback<List<Account>>() {
                @Override
                public void onResponse(Call<List<Account>> call, Response<List<Account>> response) {
                    if (response.isSuccessful()) {
                        searchView.swapSuggestions(response.body());
                        searchView.hideProgress();
                    } else {
                        searchView.hideProgress();
                    }
                }

                @Override
                public void onFailure(Call<List<Account>> call, Throwable t) {
                    searchView.hideProgress();
                }
            });
        }
    });

    searchView.setOnSearchListener(new FloatingSearchView.OnSearchListener() {
        @Override
        public void onSuggestionClicked(SearchSuggestion searchSuggestion) {
            Account accountSuggestion = (Account) searchSuggestion;
            Intent intent = new Intent(MainActivity.this, AccountActivity.class);
            intent.putExtra("id", accountSuggestion.id);
            startActivity(intent);
        }

        @Override
        public void onSearchAction(String currentQuery) {

        }
    });

    searchView.setOnBindSuggestionCallback(new SearchSuggestionsAdapter.OnBindSuggestionCallback() {
        @Override
        public void onBindSuggestion(View suggestionView, ImageView leftIcon, TextView textView,
                SearchSuggestion item, int itemPosition) {
            Account accountSuggestion = ((Account) item);

            Picasso.with(MainActivity.this).load(accountSuggestion.avatar)
                    .placeholder(R.drawable.avatar_default).into(leftIcon);

            String searchStr = accountSuggestion.getDisplayName() + " " + accountSuggestion.username;
            final SpannableStringBuilder str = new SpannableStringBuilder(searchStr);

            str.setSpan(new StyleSpan(Typeface.BOLD), 0, accountSuggestion.getDisplayName().length(),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            textView.setText(str);
            textView.setMaxLines(1);
            textView.setEllipsize(TextUtils.TruncateAt.END);
        }
    });
}