List of usage examples for android.text SpannableStringBuilder SpannableStringBuilder
public SpannableStringBuilder(CharSequence text)
From source file:com.gdgdevfest.android.apps.devfestbcn.ui.PlusStreamRowViewBinder.java
public static void bindActivityView(final View rootView, Activity activity, ImageLoader imageLoader, boolean singleSourceMode) { // Prepare view holder. ViewHolder tempViews = (ViewHolder) rootView.getTag(); final ViewHolder views; if (tempViews != null) { views = tempViews;//from w w w .j av a 2 s. c o m } else { views = new ViewHolder(); rootView.setTag(views); // Author and metadata box views.authorContainer = rootView.findViewById(R.id.stream_author_container); views.userImage = (ImageView) rootView.findViewById(R.id.stream_user_image); views.userName = (TextView) rootView.findViewById(R.id.stream_user_name); views.time = (TextView) rootView.findViewById(R.id.stream_time); // Author's content views.content = (TextView) rootView.findViewById(R.id.stream_content); // Original share box views.originalContainer = rootView.findViewById(R.id.stream_original_container); views.originalAuthor = (TextView) rootView.findViewById(R.id.stream_original_author); views.originalContent = (TextView) rootView.findViewById(R.id.stream_original_content); // Media box views.mediaContainer = rootView.findViewById(R.id.stream_media_container); views.mediaBackground = (ImageView) rootView.findViewById(R.id.stream_media_background); views.mediaOverlay = (ImageView) rootView.findViewById(R.id.stream_media_overlay); views.mediaTitle = (TextView) rootView.findViewById(R.id.stream_media_title); views.mediaSubtitle = (TextView) rootView.findViewById(R.id.stream_media_subtitle); // Interactions box views.interactionsContainer = rootView.findViewById(R.id.stream_interactions_container); views.plusOnes = (TextView) rootView.findViewById(R.id.stream_plus_ones); views.shares = (TextView) rootView.findViewById(R.id.stream_shares); views.comments = (TextView) rootView.findViewById(R.id.stream_comments); } final Context context = rootView.getContext(); final Resources res = context.getResources(); // Determine if this is a reshare (affects how activity fields are to be interpreted). Activity.PlusObject.Actor originalAuthor = activity.getObject().getActor(); boolean isReshare = "share".equals(activity.getVerb()) && originalAuthor != null; // Author and metadata box views.authorContainer.setVisibility(singleSourceMode ? View.GONE : View.VISIBLE); views.userName.setText(activity.getActor().getDisplayName()); // Find user profile image url String userImageUrl = null; if (activity.getActor().getImage() != null) { userImageUrl = activity.getActor().getImage().getUrl(); } // Load image from network in background thread using Volley library imageLoader.get(userImageUrl, views.userImage, PLACEHOLDER_USER_IMAGE); long thenUTC = activity.getUpdated().getValue() + activity.getUpdated().getTimeZoneShift() * 60000; views.time.setText(DateUtils.getRelativeTimeSpanString(thenUTC, System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS, DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_ABBREV_RELATIVE)); // Author's additional content String selfContent = isReshare ? activity.getAnnotation() : activity.getObject().getContent(); views.content.setMaxLines(singleSourceMode ? 1000 : 5); if (!TextUtils.isEmpty(selfContent)) { views.content.setVisibility(View.VISIBLE); views.content.setText(Html.fromHtml(selfContent)); } else { views.content.setVisibility(View.GONE); } // Original share box if (isReshare) { views.originalContainer.setVisibility(View.VISIBLE); // Set original author text, highlight author name final String author = res.getString(R.string.stream_originally_shared, originalAuthor.getDisplayName()); final SpannableStringBuilder spannableAuthor = new SpannableStringBuilder(author); spannableAuthor.setSpan(new StyleSpan(Typeface.BOLD), author.length() - originalAuthor.getDisplayName().length(), author.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); views.originalAuthor.setText(spannableAuthor, TextView.BufferType.SPANNABLE); String originalContent = activity.getObject().getContent(); views.originalContent.setMaxLines(singleSourceMode ? 1000 : 3); if (!TextUtils.isEmpty(originalContent)) { views.originalContent.setVisibility(View.VISIBLE); views.originalContent.setText(Html.fromHtml(originalContent)); } else { views.originalContent.setVisibility(View.GONE); } } else { views.originalContainer.setVisibility(View.GONE); } // Media box // Set media content. List<Activity.PlusObject.Attachments> attachments = activity.getObject().getAttachments(); if (attachments != null && attachments.size() > 0) { Activity.PlusObject.Attachments attachment = attachments.get(0); String objectType = attachment.getObjectType(); String imageUrl = attachment.getImage() != null ? attachment.getImage().getUrl() : null; if (imageUrl == null && attachment.getThumbnails() != null && attachment.getThumbnails().size() > 0) { Thumbnails thumb = attachment.getThumbnails().get(0); imageUrl = thumb.getImage() != null ? thumb.getImage().getUrl() : null; } // Load image from network in background thread using Volley library imageLoader.get(imageUrl, views.mediaBackground, PLACEHOLDER_MEDIA_IMAGE); boolean overlayStyle = false; views.mediaOverlay.setImageDrawable(null); if (("photo".equals(objectType) || "video".equals(objectType) || "album".equals(objectType)) && !TextUtils.isEmpty(imageUrl)) { overlayStyle = true; views.mediaOverlay .setImageResource("video".equals(objectType) ? R.drawable.ic_stream_media_overlay_video : R.drawable.ic_stream_media_overlay_photo); } else if ("article".equals(objectType) || "event".equals(objectType)) { overlayStyle = false; views.mediaTitle.setText(attachment.getDisplayName()); if (!TextUtils.isEmpty(attachment.getUrl())) { Uri uri = Uri.parse(attachment.getUrl()); views.mediaSubtitle.setText(uri.getHost()); } else { views.mediaSubtitle.setText(""); } } views.mediaContainer.setVisibility(View.VISIBLE); views.mediaContainer.setBackgroundResource( overlayStyle ? R.color.plus_stream_media_background : android.R.color.black); if (overlayStyle) { views.mediaBackground.clearColorFilter(); } else { views.mediaBackground.setColorFilter(res.getColor(R.color.plus_media_item_tint)); } views.mediaOverlay.setVisibility(overlayStyle ? View.VISIBLE : View.GONE); views.mediaTitle.setVisibility(overlayStyle ? View.GONE : View.VISIBLE); views.mediaSubtitle.setVisibility(overlayStyle ? View.GONE : View.VISIBLE); } else { views.mediaContainer.setVisibility(View.GONE); views.mediaBackground.setImageDrawable(null); views.mediaOverlay.setImageDrawable(null); } // Interactions box final int plusOneCount = (activity.getObject().getPlusoners() != null) ? activity.getObject().getPlusoners().getTotalItems().intValue() : 0; if (plusOneCount > 0) { views.plusOnes.setVisibility(View.VISIBLE); views.plusOnes.setText(getPlusOneString(plusOneCount)); } else { views.plusOnes.setVisibility(View.GONE); } final int commentCount = (activity.getObject().getReplies() != null) ? activity.getObject().getReplies().getTotalItems().intValue() : 0; if (commentCount > 0) { views.comments.setVisibility(View.VISIBLE); views.comments.setText(Integer.toString(commentCount)); } else { views.comments.setVisibility(View.GONE); } final int resharerCount = (activity.getObject().getResharers() != null) ? activity.getObject().getResharers().getTotalItems().intValue() : 0; if (resharerCount > 0) { views.shares.setVisibility(View.VISIBLE); views.shares.setText(Integer.toString(resharerCount)); } else { views.shares.setVisibility(View.GONE); } views.interactionsContainer.setVisibility( (plusOneCount > 0 || commentCount > 0 || resharerCount > 0) ? View.VISIBLE : View.GONE); }
From source file:com.tct.mail.browse.SubjectAndFolderView.java
public void setFolders(ConversationViewHeaderCallbacks callbacks, Account account, Conversation conv) { mVisibleFolders = true;/*from w w w .j a v a2s .c o m*/ final BidiFormatter bidiFormatter = getBidiFormatter(); if (TextUtils.isEmpty(mSubject)) { mSubject = conv.subject; } final SpannableStringBuilder sb = new SpannableStringBuilder(bidiFormatter.unicodeWrap(mSubject)); sb.append('\u0020'); final Settings settings = account.settings; final int start = sb.length(); if (settings.importanceMarkersEnabled && conv.isImportant()) { sb.append(".\u0020"); sb.setSpan(new DynamicDrawableSpan(DynamicDrawableSpan.ALIGN_BASELINE) { @Override public Drawable getDrawable() { Drawable d = getContext().getResources() .getDrawable(R.drawable.ic_email_caret_none_important_unread); d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); return d; } }, start, start + 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); } //TS: yanhua.chen 2015-12-22 EMAIL BUGFIX_1178365 MOD_S // mFolderDisplayer.loadConversationFolders(conv, null /* ignoreFolder */, -1 /* ignoreFolderType */); // mFolderDisplayer.appendFolderSpans(sb, bidiFormatter); // final int end = sb.length(); // sb.setSpan(new ChangeLabelsSpan(callbacks), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); setText(sb); //TS: yanhua.chen 2015-11-4 EMAIL BUGFIX_851207 MOD_S // if(isNeedMove()){ // setMovementMethod(LinkMovementMethod.getInstance()); // } //TS: yanhua.chen 2015-11-4 EMAIL BUGFIX_851207 MOD_E //TS: yanhua.chen 2015-12-22 EMAIL BUGFIX_1178365 MOD_E }
From source file:tk.wasdennnoch.androidn_ify.utils.NotificationColorUtil.java
/** * Inverts all the grayscale colors set by {@link TextAppearanceSpan}s on * the text.//from w ww .j a v a 2s .c om * * @param charSequence The text to process. * @return The color inverted text. */ public CharSequence invertCharSequenceColors(CharSequence charSequence) { if (charSequence instanceof Spanned) { Spanned ss = (Spanned) charSequence; Object[] spans = ss.getSpans(0, ss.length(), Object.class); SpannableStringBuilder builder = new SpannableStringBuilder(ss.toString()); for (Object span : spans) { Object resultSpan = span; if (span instanceof TextAppearanceSpan) { resultSpan = processTextAppearanceSpan((TextAppearanceSpan) span); } builder.setSpan(resultSpan, ss.getSpanStart(span), ss.getSpanEnd(span), ss.getSpanFlags(span)); } return builder; } return charSequence; }
From source file:cn.wjh1119.bestnews.ui.fragment.DetailFragment.java
@Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data != null && data.moveToFirst()) { //?????view FetchDetailDataFromSqlTask fetchDetailDataFromSqlTask = new FetchDetailDataFromSqlTask(); fetchDetailDataFromSqlTask/* w w w . j a va 2 s . com*/ .setOnDataFinishedListener(new FetchDetailDataFromSqlTask.OnDataFinishedListener() { @Override public void onDataSuccessfully(HashMap data) { String title = data.get("title").toString(); String source = data.get("source").toString(); String pubDate = data.get("pubDate").toString(); String content = data.get("content").toString(); String link = data.get("link").toString(); // BitmapDrawable drawable = (BitmapDrawable) data.get("drawable"); Object imageTextFromSql = data.get("imageUrl"); String imageUrl = null; if (imageTextFromSql != null) { imageUrl = data.get("imageUrl").toString(); } mTitleView.setText(title); mTitleView.setFocusable(true); mTitleView.setFocusableInTouchMode(true); mTitleView.requestFocus(); TextPaint paint = mTitleView.getPaint(); paint.setFakeBoldText(true); mSourceView.setText(source); mPubDateView.setText(pubDate); mContentView.setText(content); if (imageUrl != null) { Bitmap bitmap = imageManager.showCacheBitmap(imageUrl); if (bitmap != null) { mImageView.setImageBitmap(bitmap); } else { imageManager.downloadImage(imageUrl, new ImageManager.onImageLoaderListener() { @Override public void onImageLoader(Bitmap bitmap, String url) { if (bitmap != null) { mImageView.setImageBitmap(bitmap); } else { mImageView.setImageResource(R.mipmap.picture_fail_loading); } } }); } } SpannableStringBuilder ssb = new SpannableStringBuilder("??"); ssb.setSpan(new URLSpan(link), 0, ssb.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); ForegroundColorSpan span = new ForegroundColorSpan(Color.BLUE); ssb.setSpan(span, 0, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); mLinkView.setText(ssb); // ??MovementMethod mLinkView.setMovementMethod(LinkMovementMethod.getInstance()); // ??ClickableSpan mLinkView.setHighlightColor(0xff8FABCC); } @Override public void onDataFailed() { } }); fetchDetailDataFromSqlTask.execute(data); } AppCompatActivity activity = (AppCompatActivity) getActivity(); Toolbar toolbarView = (Toolbar) getView().findViewById(R.id.toolbar_detail); // We need to start the enter transition after the data has loaded if (mTransitionAnimation) { activity.supportStartPostponedEnterTransition(); if (null != toolbarView) { activity.setSupportActionBar(toolbarView); activity.getSupportActionBar().setDisplayShowTitleEnabled(false); activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true); } } else { if (null != toolbarView) { Menu menu = toolbarView.getMenu(); if (null != menu) menu.clear(); } } }
From source file:io.plaidapp.ui.widget.CollapsingTitleLayout.java
private void recalculate(int width) { // reset stateful objects that might change over measure passes paint.setTextSize(collapsedTextSize); displayText = new SpannableStringBuilder(title); // Calculate line height; ensure it' a multiple of 4dp to sit on the grid final float fourDip = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics()); Paint.FontMetricsInt fm = paint.getFontMetricsInt(); int fontHeight = Math.abs(fm.ascent - fm.descent) + fm.leading; final int baselineAlignedLineHeight = (int) (fourDip * (float) Math.ceil(lineHeightHint / fourDip)); final int lineSpacingAdd = baselineAlignedLineHeight - fontHeight; // now create the layout with our desired insets & line height createLayout(width, lineSpacingAdd); // adjust the displayText top inset to vertically center text with the toolbar collapsedHeight = (int) Math.max(ViewUtils.getActionBarSize(getContext()), (fourDip + baselineAlignedLineHeight + fourDip)); titleInsetTop = (collapsedHeight - baselineAlignedLineHeight) / 2f; if (lineCount == 1) { // single line mode layout = null;/* w w w .ja v a2 s . c om*/ collapsingText = new CollapsingTextHelper(this); collapsingText.setText(title); collapsingText.setCollapsedBounds(titleInsetStart, 0, width - titleInsetEnd, (int) collapsedHeight); collapsingText.setExpandedBounds(titleInsetStart, (int) titleInsetTop, width - titleInsetEnd, getMinimumHeight() - titleInsetBottom); collapsingText.setCollapsedTextColor(paint.getColor()); collapsingText.setExpandedTextColor(paint.getColor()); collapsingText.setCollapsedTextSize(collapsedTextSize); int expandedTitleTextSize = (int) Math.max(collapsedTextSize, ViewUtils.getSingleLineTextSize(displayText.toString(), paint, width - titleInsetStart - titleInsetEnd, collapsedTextSize, maxExpandedTextSize, 0.5f, getResources().getDisplayMetrics())); collapsingText.setExpandedTextSize(expandedTitleTextSize); collapsingText.setExpandedTextGravity(GravityCompat.START | Gravity.BOTTOM); collapsingText.setCollapsedTextGravity(GravityCompat.START | Gravity.CENTER_VERTICAL); collapsingText.setTypeface(paint.getTypeface()); fm = paint.getFontMetricsInt(); fontHeight = Math.abs(fm.ascent - fm.descent) + fm.leading; textTop = getHeight() - titleInsetBottom - fontHeight; scrollRange = getMinimumHeight() - (int) collapsedHeight; } else { // multi-line mode // bottom align the text textTop = getDesiredHeight() - titleInsetBottom - layout.getHeight(); // pre-calculate at what scroll offsets lines should disappear scrollRange = (int) (textTop - titleInsetTop); final int fadeDistance = lineSpacingAdd + fm.descent; // line bottom to baseline lines = new Line[lineCount]; for (int i = 1; i < lineCount; i++) { int lineBottomScrollOffset = scrollRange + ((lineCount - i - 1) * baselineAlignedLineHeight); lines[i] = new Line(layout.getLineStart(i), layout.getLineEnd(i), new ForegroundColorSpan(paint.getColor()), lineBottomScrollOffset, lineBottomScrollOffset + fadeDistance); } } calculatedWithWidth = width; }
From source file:com.ruesga.rview.misc.Formatter.java
@BindingAdapter("userMessage") public static void toUserMessage(TextView view, String msg) { if (msg == null) { view.setText(null);//from w w w . j a v a 2s . c o m return; } String message = EmojiHelper.createEmoji(msg); // This process mimics the Gerrit formatting process done in class // ./gerrit-gwtexpui/src/main/java/com/google/gwtexpui/safehtml/client/SafeHtml.java // Split message into paragraphs String[] paragraphs = StringHelper.obtainParagraphs(message); StringBuilder sb = new StringBuilder(); boolean formattedMessage = false; for (String p : paragraphs) { if (StringHelper.isQuote(p)) { sb.append(StringHelper.obtainQuote(StringHelper.removeLineBreaks(p))); formattedMessage = true; } else if (StringHelper.isList(p)) { sb.append(p); formattedMessage = true; } else if (StringHelper.isPreFormat(p)) { sb.append(StringHelper.obtainPreFormatMessage(p)); formattedMessage = true; } else { sb.append(p); } sb.append("\n\n"); } String userMessage = StringHelper.removeExtraLines(sb.toString()); if (!formattedMessage) { view.setText(userMessage); return; } if (sQuoteColor == -1) { sQuoteColor = ContextCompat.getColor(view.getContext(), R.color.quote); sQuoteWidth = (int) view.getContext().getResources().getDimension(R.dimen.quote_width); sQuoteMargin = (int) view.getContext().getResources().getDimension(R.dimen.quote_margin); } String[] lines = userMessage.split("\n"); SpannableStringBuilder spannable = new SpannableStringBuilder(userMessage .replaceAll(StringHelper.NON_PRINTABLE_CHAR, "").replaceAll(StringHelper.NON_PRINTABLE_CHAR2, "")); // Pre-Format int start = 0; int spans = 0; while ((start = userMessage.indexOf(StringHelper.NON_PRINTABLE_CHAR2, start)) != -1) { int end = userMessage.indexOf(StringHelper.NON_PRINTABLE_CHAR2, start + 1); if (end == -1) { //? This is supposed to be formatted by us. Skip it break; } // Find quote token occurrences int offset = StringHelper.countOccurrences(StringHelper.NON_PRINTABLE_CHAR, userMessage, 0, start); start -= offset; end -= offset; // Ensure bounds int spanStart = start - spans; int spanEnd = Math.min(end - spans - 1, spannable.length()); if (spanStart < 0 || spanEnd < 0) { //Something was wrong. Skip it break; } spannable.setSpan(new RelativeSizeSpan(0.8f), spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); spannable.setSpan(new TypefaceSpan("monospace"), spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); start = end; spans++; } start = 0; for (String line : lines) { // Quotes int maxIndent = StringHelper.countOccurrences(StringHelper.NON_PRINTABLE_CHAR, line); for (int i = 0; i < maxIndent; i++) { QuotedSpan span = new QuotedSpan(sQuoteColor, sQuoteWidth, sQuoteMargin); spannable.setSpan(span, start, Math.min(start + line.length() - maxIndent, spannable.length()), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } // List if (StringHelper.isList(line)) { spannable.replace(start, start + 1, "\u2022"); spannable.setSpan(new LeadingMarginSpan.Standard(sQuoteMargin), start, Math.min(start + line.length(), spannable.length()), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } start += line.length() - maxIndent + 1; } view.setText(spannable); }
From source file:at.jclehner.rxdroid.DoseView.java
private void updateView() { mStatus = STATUS_INDETERMINATE;/*ww w . j a va 2s . co m*/ mIntakeStatus.setImageDrawable(null); if (mDrug != null) { if (!mDrug.isActive()) mDoseText.setText("0"); else if (!mDisplayDose.isZero()) { setStatus(STATUS_TAKEN); SpannableStringBuilder sb = new SpannableStringBuilder(Util.prettify(mDisplayDose)); final Date lastScheduleUpdate = mDrug.getLastScheduleUpdateDate(); if (lastScheduleUpdate == null || !mDate.before(lastScheduleUpdate)) { final Fraction scheduledDose = mDrug.getDose(mDoseTime, mDate); int cmp = mDisplayDose.compareTo(scheduledDose); String suffix; if (cmp < 0) suffix = "-"; else if (cmp > 0) suffix = "+"; else suffix = null; if (suffix != null) { sb.append(suffix); sb.setSpan(new SuperscriptSpan(), sb.length() - 1, sb.length(), 0); } } mDoseText.setText(sb); } else { Fraction dose = mDrug.getDose(mDoseTime, mDate); mDoseText.setText(Util.prettify(dose)); if (mIntakeCount == 0) { if (!dose.isZero() && !mDrug.isAsNeeded()) { int offset = (int) Settings.getTrueDoseTimeEndOffset(mDoseTime); Date end = DateTime.add(mDate, Calendar.MILLISECOND, offset); if (DateTime.now().after(end)) setStatus(STATUS_MISSED); } } else setStatus(STATUS_IGNORED); } } else if (mDisplayDose != null) mDoseText.setText(Util.prettify(mDisplayDose)); if ("0".equals(mDoseText.getText())) { String zeroStr = null; if (BuildConfig.DEBUG) zeroStr = Settings.getString("doseview_zero"); if (zeroStr == null) zeroStr = "-"; mDoseText.setText(zeroStr); } }
From source file:ca.rmen.android.poetassistant.main.dictionaries.ResultListFragment.java
private void updateUi() { Log.d(TAG, mTab + ": updateUi() called with: " + ""); if (mAdapter.getItemCount() > 0 || !TextUtils.isEmpty(mHeaderFragment.getHeader())) { mHeaderFragment.show();//from w ww . java 2 s.c o m } else { mHeaderFragment.hide(); } String query = mData == null ? null : mData.matchedWord; mHeaderFragment.setHeader(query); // If we have an empty list because the user didn't enter any search term, // we'll show a text to tell them to search. if (TextUtils.isEmpty(query)) { String emptySearch = getString(R.string.empty_list_without_query); ImageSpan imageSpan = VectorCompat.createVectorImageSpan(getActivity(), R.drawable.ic_action_search_dark); SpannableStringBuilder ssb = new SpannableStringBuilder(emptySearch); int iconIndex = emptySearch.indexOf("%s"); ssb.setSpan(imageSpan, iconIndex, iconIndex + 2, Spannable.SPAN_INCLUSIVE_INCLUSIVE); mBinding.empty.setText(ssb, TextView.BufferType.SPANNABLE); } // If the user entered a query and there are no matches, show the normal "no results" text. else { String noResults = ResultListFactory.getEmptyListText(getContext(), mTab, query); mBinding.empty.setText(noResults); } if (mData == null || mData.data.isEmpty()) { mBinding.empty.setVisibility(View.VISIBLE); mBinding.recyclerView.setVisibility(View.GONE); } else { mBinding.empty.setVisibility(View.GONE); mBinding.recyclerView.setVisibility(View.VISIBLE); } if (mData != null) mHeaderFragment.setFavorite(mData.isFavorite); getActivity().supportInvalidateOptionsMenu(); }
From source file:com.hannesdorfmann.home.HomeActivity.java
private void setNoFiltersVisiblity(int visibility) { if (visibility == View.VISIBLE) { if (noFiltersEmptyText == null) { // create the no filters empty text ViewStub stub = (ViewStub) findViewById(R.id.stub_no_filters); noFiltersEmptyText = (TextView) stub.inflate(); String emptyText = getString(R.string.no_filters_selected); int filterPlaceholderStart = emptyText.indexOf('\u08B4'); int altMethodStart = filterPlaceholderStart + 3; SpannableStringBuilder ssb = new SpannableStringBuilder(emptyText); // show an image of the filter icon ssb.setSpan(new ImageSpan(this, R.drawable.ic_filter_small, ImageSpan.ALIGN_BASELINE), filterPlaceholderStart, filterPlaceholderStart + 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); noFiltersEmptyText.setText(ssb); noFiltersEmptyText.setOnClickListener(new View.OnClickListener() { @Override//from w w w.j a v a2 s. c o m public void onClick(View v) { drawer.openDrawer(GravityCompat.END); } }); } noFiltersEmptyText.setVisibility(visibility); } else if (noFiltersEmptyText != null) { noFiltersEmptyText.setVisibility(visibility); } }
From source file:com.amitupadhyay.aboutexample.ui.widget.CollapsingTitleLayout.java
private void recalculate(int width) { // reset stateful objects that might change over measure passes paint.setTextSize(collapsedTextSize); displayText = new SpannableStringBuilder(title); // Calculate line height; ensure it' a multiple of 4dp to sit on the grid final float fourDip = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics()); Paint.FontMetricsInt fm = paint.getFontMetricsInt(); int fontHeight = Math.abs(fm.ascent - fm.descent) + fm.leading; final int baselineAlignedLineHeight = (int) (fourDip * (float) Math.ceil(lineHeightHint / fourDip)); lineSpacingAdd = Math.max(0, baselineAlignedLineHeight - fontHeight); // now create the layout with our desired insets & line height createLayout(width, lineSpacingAdd); // adjust the title top inset to vertically center text with the toolbar collapsedHeight = (int) Math.max(ViewUtils.getActionBarSize(getContext()), (fourDip + baselineAlignedLineHeight + fourDip)); titleInsetTop = (collapsedHeight - baselineAlignedLineHeight) / 2f; if (lineCount == 1) { // single line mode layout = null;// ww w. j a v a 2 s . co m collapsingText = new CollapsingTextHelper(this); collapsingText.setText(title); collapsingText.setCollapsedBounds(titleInsetStart, 0, width - titleInsetEnd, (int) collapsedHeight); collapsingText.setExpandedBounds(titleInsetStart, (int) titleInsetTop, width - titleInsetEnd, getMinimumHeight() - titleInsetBottom); collapsingText.setCollapsedTextColor(paint.getColor()); collapsingText.setExpandedTextColor(paint.getColor()); collapsingText.setCollapsedTextSize(collapsedTextSize); int expandedTitleTextSize = (int) Math.max(collapsedTextSize, ViewUtils.getSingleLineTextSize(displayText.toString(), paint, width - titleInsetStart - titleInsetEnd, collapsedTextSize, maxExpandedTextSize, 0.5f, getResources().getDisplayMetrics())); collapsingText.setExpandedTextSize(expandedTitleTextSize); collapsingText.setExpandedTextGravity(GravityCompat.START | Gravity.BOTTOM); collapsingText.setCollapsedTextGravity(GravityCompat.START | Gravity.CENTER_VERTICAL); collapsingText.setTypeface(paint.getTypeface()); textTop = getHeight() - titleInsetBottom - fontHeight; scrollRange = getMinimumHeight() - (int) collapsedHeight; } else { // multi-line mode // bottom align the text textTop = getDesiredHeight() - titleInsetBottom - layout.getHeight(); // pre-calculate at what scroll offsets lines should disappear scrollRange = (int) (textTop - titleInsetTop); final int fadeDistance = layout.getLineBottom(0) - layout.getLineBaseline(0); lines = new Line[lineCount]; for (int i = 1; i < lineCount; i++) { int lineBottomScrollOffset = scrollRange + ((lineCount - i - 1) * baselineAlignedLineHeight); lines[i] = new Line(layout.getLineStart(i), layout.getLineEnd(i), new TextColorSpan(paint.getColor()), lineBottomScrollOffset, lineBottomScrollOffset + fadeDistance); } } calculatedWithWidth = width; }