@Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); SpannableString ss = new SpannableString(getString(R.string.pick_csv_or_demo_file)); ClickableSpan clickableSpan = new ClickableSpan() { @Override public void onClick(View textView) { if (PermissionHelper.checkOrRequest(CsvPickerFragment.this, REQUEST_CODE_PERMISSION_READ_EXTERNAL_STORAGE_DEMO, Manifest.permission.READ_EXTERNAL_STORAGE)) { createDemoFile(); } } @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); ds.setUnderlineText(false); } }; ss.setSpan(clickableSpan, 32, 36, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); tvPickFile.setText(ss); tvPickFile.setMovementMethod(LinkMovementMethod.getInstance()); tvPickFile.setHighlightColor(Color.TRANSPARENT); }
/** * 解析URL和电话号码并高亮显示 */ private SpannableString changeToLight(String str) { SpannableString string = new SpannableString(str); for (Pattern p : mPatterns) { Matcher m = p.matcher(string); while (m.find()) { int start = m.start(); int end = m.end(); string.setSpan(new ClickableSpan() { @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); ds.setColor(getColors(R.color.color_theme)); } @Override public void onClick(View widget) { } }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } return string; }
private Spannable genTimeAndReplyText(final Comment comment) { String time = AppTextUtils.getDateFromUnixTime(comment.getDate()); if (comment.getReplyToUser() == 0) { return Spannable.Factory.getInstance().newSpannable(time); } String commentText = context.getString(R.string.comment).toLowerCase(); String target = context.getString(R.string.in_response_to, time, commentText); int start = target.indexOf(commentText); Spannable spannable = Spannable.Factory.getInstance().newSpannable(target); ClickableSpan span = new ClickableSpan() { @Override public void onClick(View widget) { onReplyClick(comment.getReplyToUser(), comment.getReplyToComment()); } }; spannable.setSpan(span, start, target.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); return spannable; }
public static void makeLinksClickable(TextView v) { SpannableStringBuilder ssb = new SpannableStringBuilder(v.getText()); URLSpan[] spans = ssb.getSpans(0, ssb.length(), URLSpan.class); for (URLSpan span : spans) { int start = ssb.getSpanStart(span); int end = ssb.getSpanEnd(span); final String url = span.getURL(); ssb.removeSpan(span); ClickableSpan cSpan = new ClickableSpan() { @Override public void onClick(View v2) { LinkDialogFragment f = LinkDialogFragment.newInstance(url); FragmentManager fm = ((AppCompatActivity) v2.getContext()) .getSupportFragmentManager(); f.show(fm, f.getUniqueTag()); } }; ssb.setSpan(cSpan, start, end, 0); } v.setText(ssb); v.setMovementMethod(ArticleMovementMethod.getInstance()); }
/** * 获取超链接字段 * @return 超链接字符串 */ private SpannableString getClickableSpan(String aStr) { int startIndex = aStr.indexOf(mAuthorName); int endIndex = startIndex + mAuthorName.length(); SpannableString spannableString = new SpannableString(aStr); //设置下划线文字 // spannableString.setSpan(new UnderlineSpan(), startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); //设置文字的单击事件 spannableString.setSpan(new ClickableSpan() { @Override public void onClick(View widget) { Uri uri = Uri.parse(mExtLink); Context context = widget.getContext(); Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName()); context.startActivity(intent); } }, startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); //设置文字的前景色 spannableString.setSpan(new ForegroundColorSpan(ThemeStyle.Accent), startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); return spannableString; }
private CharSequence prepareMainMessageString(final PermissionDialogDelegate delegate) { SpannableStringBuilder fullString = new SpannableStringBuilder(); String messageText = delegate.getMessageText(); String linkText = delegate.getLinkText(); if (!TextUtils.isEmpty(messageText)) fullString.append(messageText); // If the linkText exists, then wrap it in a clickable span and concatenate it with the main // dialog message. if (!TextUtils.isEmpty(linkText)) { if (fullString.length() > 0) fullString.append(" "); int spanStart = fullString.length(); fullString.append(linkText); fullString.setSpan(new ClickableSpan() { @Override public void onClick(View view) { mDecision = NOT_DECIDED; delegate.onLinkClicked(); if (mDialog != null) mDialog.dismiss(); } }, spanStart, fullString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } return fullString; }
private SpannableString getDescriptionText() { return SpanApplier.applySpans( getString(R.string.physical_web_optin_description), new SpanInfo("<learnmore>", "</learnmore>", new ClickableSpan() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(PHYSICAL_WEB_LEARN_MORE_URL)); // Add the SESSION extra to indicate we want a Chrome custom tab. This // allows the help page to open in the same task as the opt-in activity so // they can share a back stack. String session = null; intent.putExtra(EXTRA_CUSTOM_TABS_SESSION, session); PhysicalWebOptInActivity.this.startActivity(intent); } @Override public void updateDrawState(TextPaint ds) { // Color links but do not underline them. ds.setColor(ds.linkColor); } })); }
private SpannableString getResetText() { final Context context = getActivity(); return SpanApplier.applySpans( context.getString(R.string.sync_passphrase_encryption_reset_instructions), new SpanInfo("<resetlink>", "</resetlink>", new ClickableSpan() { @Override public void onClick(View view) { Uri syncDashboardUrl = Uri.parse( context.getText(R.string.sync_dashboard_url).toString()); Intent intent = new Intent(Intent.ACTION_VIEW, syncDashboardUrl); intent.setPackage(BuildInfo.getPackageName(context)); IntentUtils.safePutBinderExtra( intent, CustomTabsIntent.EXTRA_SESSION, null); context.startActivity(intent); } })); }
private SpannableString getResetText() { final Context context = getActivity(); return SpanApplier.applySpans( context.getString(R.string.sync_passphrase_reset_instructions), new SpanInfo("<resetlink>", "</resetlink>", new ClickableSpan() { @Override public void onClick(View view) { recordPassphraseDialogDismissal(PASSPHRASE_DIALOG_RESET_LINK); Uri syncDashboardUrl = Uri.parse( context.getText(R.string.sync_dashboard_url).toString()); Intent intent = new Intent(Intent.ACTION_VIEW, syncDashboardUrl); intent.setPackage(BuildInfo.getPackageName(context)); IntentUtils.safePutBinderExtra( intent, CustomTabsIntent.EXTRA_SESSION, null); context.startActivity(intent); } })); }
@Override public void createContent(InfoBarLayout layout) { super.createContent(layout); if (mTitleLinkRangeStart != 0 && mTitleLinkRangeEnd != 0) { SpannableString title = new SpannableString(mTitle); title.setSpan(new ClickableSpan() { @Override public void onClick(View view) { onLinkClicked(); } }, mTitleLinkRangeStart, mTitleLinkRangeEnd, Spanned.SPAN_INCLUSIVE_INCLUSIVE); layout.setMessage(title); } InfoBarControlLayout controlLayout = layout.addControlLayout(); if (mUsernames.length > 1) { InfoBarArrayAdapter<String> usernamesAdapter = new InfoBarArrayAdapter<String>(getContext(), mUsernames); mUsernamesSpinner = controlLayout.addSpinner( R.id.password_infobar_accounts_spinner, usernamesAdapter); } else { controlLayout.addDescription(mUsernames[0]); } }
/** * Gets the infobar text for offline page downloads. * @param context Context to be used. * @param template Template of the text to be displayed. */ private CharSequence getOfflinePageMessageText(final Context context, final String template) { return getMessageText(template, mFilePath, new ClickableSpan() { @Override public void onClick(View view) { // TODO(qinmin): open the offline page on local storage instead of opening the url. // However, there could be multiple stored offline pages for the same url, need to // figure out which one to use. Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(mPageUrl)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setPackage(context.getPackageName()); context.startActivity(intent); } }); }
/** * Prepares text to be displayed as the infobar's main message, including setting up a * clickable link if the infobar requires it. */ private CharSequence prepareMainMessageString() { SpannableStringBuilder fullString = new SpannableStringBuilder(); if (mMessageMainText != null) fullString.append(mMessageMainText); // Concatenate the text to display for the link and make it clickable. if (!TextUtils.isEmpty(mMessageLinkText)) { if (fullString.length() > 0) fullString.append(" "); int spanStart = fullString.length(); fullString.append(mMessageLinkText); fullString.setSpan(new ClickableSpan() { @Override public void onClick(View view) { mInfoBarView.onLinkClicked(); } }, spanStart, fullString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } return fullString; }
@Override public void createContent(InfoBarLayout layout) { super.createContent(layout); InfoBarControlLayout control = layout.addControlLayout(); for (int i = 0; i < mCardDetails.size(); i++) { CardDetail detail = mCardDetails.get(i); control.addIcon(detail.issuerIconDrawableId, 0, detail.label, detail.subLabel); } for (LegalMessageLine line : mLegalMessageLines) { SpannableString text = new SpannableString(line.text); for (final LegalMessageLine.Link link : line.links) { text.setSpan(new ClickableSpan() { @Override public void onClick(View view) { nativeOnLegalMessageLinkClicked(mNativeAutofillSaveCardInfoBar, link.url); } }, link.start, link.end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); } control.addDescription(text); } }
@Override public void createContent(InfoBarLayout layout) { super.createContent(layout); SpannableString message = new SpannableString(mMessageText); message.setSpan( new ClickableSpan() { @Override public void onClick(View view) { onLinkClicked(); } @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); ds.setUnderlineText(false); } }, mInlineLinkRangeStart, mInlineLinkRangeEnd, Spanned.SPAN_INCLUSIVE_INCLUSIVE); layout.setMessage(message); }
private void setSpans(final Tag tag) { final TagSpan tagSpan = recycleTag(tag); final ClickableSpan clickableSpan = new ClickableSpan() { @Override public void onClick(final View widget) { removeSpan(tag); } }; getText().setSpan( tagSpan, tag.getStartIndex(), tag.getEndIndex(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); getText().setSpan( clickableSpan, tag.getStartIndex(), tag.getEndIndex(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); }
private BetterLinkMovementExtended.ClickableSpanWithText findClickableSpanUnderTouch(TextView textView, Spannable text, MotionEvent event) { int touchX = (int) event.getX(); int touchY = (int) event.getY(); touchX -= textView.getTotalPaddingLeft(); touchY -= textView.getTotalPaddingTop(); touchX += textView.getScrollX(); touchY += textView.getScrollY(); Layout layout = textView.getLayout(); int touchedLine = layout.getLineForVertical(touchY); int touchOffset = layout.getOffsetForHorizontal(touchedLine, (float) touchX); this.touchedLineBounds.left = layout.getLineLeft(touchedLine); this.touchedLineBounds.top = (float) layout.getLineTop(touchedLine); this.touchedLineBounds.right = layout.getLineWidth(touchedLine) + this.touchedLineBounds.left; this.touchedLineBounds.bottom = (float) layout.getLineBottom(touchedLine); if (this.touchedLineBounds.contains((float) touchX, (float) touchY)) { Object[] spans = text.getSpans(touchOffset, touchOffset, SPAN_CLASS); for (Object span : spans) { if (span instanceof ClickableSpan) { return ClickableSpanWithText.ofSpan(textView, (ClickableSpan) span); } } return null; } else { return null; } }
public static boolean handleClickableSpan(View view, Layout layout, Spannable buffer, MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) { int x = (int) event.getX(); int y = (int) event.getY(); x -= view.getPaddingLeft(); y -= view.getPaddingTop(); x += view.getScrollX(); y += view.getScrollY(); int line = layout.getLineForVertical(y); int off = layout.getOffsetForHorizontal(line, x); ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class); if (link.length != 0) { if (action == MotionEvent.ACTION_UP) { link[0].onClick(view); } else { Selection.setSelection(buffer, buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0])); } return true; } else { Selection.removeSelection(buffer); } } return false; }
/** * 格式化git项目标签 */ static Spannable parseOnlyGit(final Context context, CharSequence content) { SpannableStringBuilder builder = new SpannableStringBuilder(content); Matcher matcher; while (true) { matcher = PatternGit.matcher(builder.toString()); if (matcher.find()) { final String group0 = matcher.group(2); final String group1 = matcher.group(3); builder.replace(matcher.start(), matcher.end(), group1); ClickableSpan span = new ClickableSpan() { @Override public void onClick(View widget) { Project project = new Project(); project.setId(Integer.parseInt(group0)); ProjectDetailActivity.show(context, project); } }; builder.setSpan(span, matcher.start(), matcher.start() + group1.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); continue; } break; } return builder; }
/** * 重写点击事件 * @return */ private ClickableSpan getClickableSpan() { return new ClickableSpan() { @Override public void onClick(View widget) { TextView tv = (TextView) widget; String word = tv.getText().toString().trim().subSequence(tv.getSelectionStart(), tv.getSelectionEnd()).toString(); setSelectedSpan(tv); if (mOnWordClickListener != null) { mOnWordClickListener.onClick(word); } } @Override public void updateDrawState(TextPaint ds) { } }; }
public static void setHtmlWithLinkClickHandler(TextView tv, String html, Action1<String> linkClickHandler) { CharSequence sequence = Html.fromHtml(html); SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence); URLSpan[] urls = strBuilder.getSpans(0, sequence.length(), URLSpan.class); for (URLSpan span : urls) { int start = strBuilder.getSpanStart(span); int end = strBuilder.getSpanEnd(span); int flags = strBuilder.getSpanFlags(span); ClickableSpan clickable = new ClickableSpan() { public void onClick(View view) { linkClickHandler.call(span.getURL()); } }; strBuilder.setSpan(clickable, start, end, flags); strBuilder.removeSpan(span); } tv.setText(strBuilder); tv.setMovementMethod(LinkMovementMethod.getInstance()); }
private void checkForLink(String message, SpannableStringBuilder spanbuilder) { linkMatcher = linkPattern.matcher(message); while(linkMatcher.find()) { final String url = linkMatcher.group(1); ClickableSpan clickableSpan = new ClickableSpan() { @Override public void onClick(View view) { CustomTabsIntent.Builder mTabs = new CustomTabsIntent.Builder(); mTabs.setStartAnimations(context, R.anim.slide_in_bottom_anim, R.anim.fade_out_semi_anim); mTabs.setExitAnimations(context, R.anim.fade_in_semi_anim, R.anim.slide_out_bottom_anim); mTabs.build().launchUrl(context, Uri.parse(url)); Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(25); } }; int start = message.indexOf(url); spanbuilder.setSpan(clickableSpan, start, start + url.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } }
/** * 微博文本触摸监听处理 * * @param textView 点击的TextView * @param event * @return true:点击事件被处理;false:点击事件未被处理,向上冒泡 */ private boolean textTouchEvent(TextView textView, MotionEvent event) { boolean ret = false; CharSequence text = textView.getText(); Spannable sText = Spannable.Factory.getInstance().newSpannable(text); int action = event.getAction(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) { int x = (int) event.getX(); int y = (int) event.getY(); x -= textView.getTotalPaddingLeft(); y -= textView.getTotalPaddingTop(); x += textView.getScrollX(); y += textView.getScrollY(); Layout layout = textView.getLayout(); int line = layout.getLineForVertical(y); int offset = layout.getOffsetForHorizontal(line, x); ClickableSpan[] links = sText.getSpans(offset, offset, ClickableSpan.class); if (links.length != 0) { if (action == MotionEvent.ACTION_UP) { links[0].onClick(textView); } ret = true; } } return ret; }
public boolean isInFangContext() { SpannableStringBuilder builder = attributedString; ClickableSpan[] spans = builder.getSpans(0, builder.length(), ClickableSpan.class); Map<String, String> dict = SingletonData.getInstance().getFangAliasDict(); if (spans.length > 0) { ClickableSpan span = spans[0]; int start = builder.getSpanStart(span); int end = builder.getSpanEnd(span); String unit = builder.subSequence(start, end) .toString(); String left = dict.get(unit); if (left == null) { left = unit; } if (SingletonData.getInstance().getAllFang().contains(left) && start > 0 && builder.toString().substring(start - 1, start).equals("、") && builder.charAt(0) != '*') { return true; } } return false; }
public boolean isInYaoContext() { SpannableStringBuilder builder = attributedString; ClickableSpan[] spans = builder.getSpans(0, builder.length(), ClickableSpan.class); Map<String, String> dict = SingletonData.getInstance().getYaoAliasDict(); if (spans.length > 0) { ClickableSpan span = spans[0]; int start = builder.getSpanStart(span); int end = builder.getSpanEnd(span); String unit = builder.subSequence(start, end) .toString(); String left = dict.get(unit); if (left == null) { left = unit; } if (SingletonData.getInstance().getAllYao().contains(left) && start > 0 && builder.toString().substring(start - 1, start).equals("、")) { return true; } } return false; }
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { if (event.getAction() == 1) { this.mLinkClicked = false; this.mClickedLink = null; int x = (((int) event.getX()) - widget.getTotalPaddingLeft()) + widget.getScrollX(); int y = (((int) event.getY()) - widget.getTotalPaddingTop()) + widget.getScrollY(); Layout layout = widget.getLayout(); int off = layout.getOffsetForHorizontal(layout.getLineForVertical(y), (float) x); ClickableSpan[] link = (ClickableSpan[]) buffer.getSpans(off, off, ClickableSpan .class); if (link.length != 0) { SensibleUrlSpan span = link[0]; this.mLinkClicked = span.onClickSpan(widget); this.mClickedLink = span.getURL(); return this.mLinkClicked; } } super.onTouchEvent(widget, buffer, event); return false; }
private void initializeLinks() { TextView failureText = (TextView) findViewById(R.id.sms_failed_text); String pretext = getString(R.string.registration_progress_activity__signal_timed_out_while_waiting_for_a_verification_sms_message); String link = getString(R.string.RegistrationProblemsActivity_possible_problems); SpannableString spannableString = new SpannableString(pretext + " " + link); spannableString.setSpan(new ClickableSpan() { @Override public void onClick(View widget) { new AlertDialog.Builder(RegistrationProgressActivity.this) .setTitle(R.string.RegistrationProblemsActivity_possible_problems) .setView(R.layout.registration_problems) .setNeutralButton(android.R.string.ok, null) .show(); } }, pretext.length() + 1, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); failureText.setText(spannableString); failureText.setMovementMethod(LinkMovementMethod.getInstance()); }
@Override public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_DOWN) { int x = (int) event.getX(); int y = (int) event.getY(); x -= widget.getTotalPaddingLeft(); y -= widget.getTotalPaddingTop(); x += widget.getScrollX(); y += widget.getScrollY(); Layout layout = widget.getLayout(); int line = layout.getLineForVertical(y); int off = layout.getOffsetForHorizontal(line, x); ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class); if (link.length != 0) { link[0].onClick(widget); return true; } else { Selection.removeSelection(buffer); } } return super.onTouchEvent(widget, buffer, event); }
@Override public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { int action = event.getActionMasked(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) { int x = (int) event.getX(); int y = (int) event.getY(); x -= widget.getTotalPaddingLeft(); y -= widget.getTotalPaddingTop(); x += widget.getScrollX(); y += widget.getScrollY(); Layout layout = widget.getLayout(); int line = layout.getLineForVertical(y); int off = layout.getOffsetForHorizontal(line, x); ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class); if (link.length > 0) { if (action == MotionEvent.ACTION_UP) { link[0].onClick(widget); } else { Selection.setSelection(buffer, buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0])); } return true; } else { Selection.removeSelection(buffer); } } return false; }
public static void setTextWithLinks(TextView textView, CharSequence html) { textView.setText(html); textView.setOnTouchListener(new View.OnTouchListener() { @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouch(View v, MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) { int x = (int) event.getX(); int y = (int) event.getY(); TextView widget = (TextView) v; x -= widget.getTotalPaddingLeft(); y -= widget.getTotalPaddingTop(); x += widget.getScrollX(); y += widget.getScrollY(); Layout layout = widget.getLayout(); int line = layout.getLineForVertical(y); int off = layout.getOffsetForHorizontal(line, x); ClickableSpan[] link = Spannable.Factory.getInstance() .newSpannable(widget.getText()) .getSpans(off, off, ClickableSpan.class); if (link.length != 0) { if (action == MotionEvent.ACTION_UP) { link[0].onClick(widget); } return true; } } return false; } }); }
private Spannable addEndTag(SpannableStringBuilder builder) { //Don't add the tag to the last section. Spine spine = bookView.getSpine(); if (spine == null || spine.getPosition() >= spine.size() -1 ) { return builder; } int length = builder.length(); builder.append("\uFFFC"); builder.append("\n"); builder.append( context.getString(R.string.end_of_section)); //If not, consider it an internal nav link. ClickableSpan span = new ClickableSpan() { @Override public void onClick(View widget) { pageDown(); } }; Drawable img = context.getResources().getDrawable(R.drawable.gateway); img.setBounds(0, 0, img.getIntrinsicWidth(), img.getIntrinsicHeight() ); builder.setSpan(new ImageSpan(img), length, length+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); builder.setSpan(span, length, builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); builder.setSpan( (AlignmentSpan) () -> Alignment.ALIGN_CENTER , length, builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return builder; }
@Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); ButterKnife.bind(this); poweredBy.setMovementMethod(LinkMovementMethod.getInstance()); String developedByText = getString(R.string.developed_by); SpannableString spannableString = new SpannableString(developedByText); ClickableSpan clickableSpan = new ClickableSpan() { @Override public void onClick(View widget) { openMyProfile(); } @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); ds.setUnderlineText(false); } }; spannableString.setSpan( clickableSpan, developedByText.indexOf('G'), developedByText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); developedBy.setText(spannableString); developedBy.setMovementMethod(LinkMovementMethod.getInstance()); developedBy.setHighlightColor(getResources().getColor(R.color.colorAccent)); }
private void bindTitle(TitleViewHolder holder) { if (mLayoutManager instanceof StaggeredGridLayoutManager) { StaggeredGridLayoutManager.LayoutParams layoutParams = new StaggeredGridLayoutManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); layoutParams.setFullSpan(true); holder.itemView.setLayoutParams(layoutParams); } final int position = holder.getAdapterPosition(); if (position == 0) { String title = mContext.getString(getTypeTitle()); String fullText = mContext.getString(R.string.who_can_have_access) + " " + title; Spannable spannable = SpannableStringBuilder.valueOf(fullText); ClickableSpan span = new ClickableSpan() { @Override public void onClick(View widget) { if(mActionListener != null){ mActionListener.onTypeClick(); } } }; spannable.setSpan(span, fullText.length() - title.length(), fullText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); holder.title.setText(spannable, TextView.BufferType.SPANNABLE); } else { holder.title.setText(R.string.who_cannot_have_access); } holder.buttonAdd.setOnClickListener(v -> { if(mActionListener != null){ if(position == 0){ mActionListener.onAddToAllowedClick(); } else { mActionListener.onAddToDisallowedClick(); } } }); }
public static ViewAction clickClickableSpan(final CharSequence textToClick) { return new ViewAction() { @Override public Matcher<View> getConstraints() { return instanceOf(TextView.class); } @Override public String getDescription() { return "clicking on a ClickableSpan"; } @Override public void perform(UiController uiController, View view) { TextView textView = (TextView) view; SpannableString spannableString = (SpannableString) textView.getText(); if (spannableString.length() == 0) { // TextView is empty, nothing to do throw new NoMatchingViewException.Builder() .includeViewHierarchy(true) .withRootView(textView) .build(); } // Get the links inside the TextView and check if we find textToClick ClickableSpan[] spans = spannableString.getSpans(0, spannableString.length(), ClickableSpan.class); if (spans.length > 0) { ClickableSpan spanCandidate; for (ClickableSpan span : spans) { spanCandidate = span; int start = spannableString.getSpanStart(spanCandidate); int end = spannableString.getSpanEnd(spanCandidate); CharSequence sequence = spannableString.subSequence(start, end); if (textToClick.toString().equals(sequence.toString())) { span.onClick(textView); return; } } } // textToClick not found in TextView throw new NoMatchingViewException.Builder() .includeViewHierarchy(true) .withRootView(textView) .build(); } }; }
public static SpannableString setTextSpannable(TextView textView, String[] strings, int[] color, final OnItemViewListener listener) { int start = 0; int end = 0; StringBuilder sb = new StringBuilder(); for (String str : strings) { if (str != null) { sb.append(str); } } SpannableString spannableString = new SpannableString(sb.toString()); for (int i = 0; i < strings.length; ++i) { if (strings[i] != null) { end += strings[i].length(); if (color.length == 1) { spannableString.setSpan(new ForegroundColorSpan(textView.getResources().getColor(color[0])), start, end, Spanned.SPAN_EXCLUSIVE_INCLUSIVE); } else if (color[i] > 0) { spannableString.setSpan(new ForegroundColorSpan(textView.getResources().getColor(color[i])), start, end, Spanned.SPAN_EXCLUSIVE_INCLUSIVE); } if (listener != null) { final int finalI = i; ClickableSpan cbs = new ClickableSpan() { @Override public void onClick(View view) { listener.onItemViewClick(null, view, finalI); } @Override public void updateDrawState(TextPaint textPaint) { textPaint.setUnderlineText(false); } }; spannableString.setSpan(cbs, start, end, Spanned.SPAN_EXCLUSIVE_INCLUSIVE); } start += strings[i].length(); } } textView.setMovementMethod(LinkMovementMethod.getInstance()); textView.setText(spannableString); return spannableString; }
@Override public boolean onTouchEvent(MotionEvent event) { // this method is currently only for detecting a ClickableSpan if (mMovementMethod != null && event.getAction() == MotionEvent.ACTION_UP) { int x = (int) event.getX(); int y = (int) event.getY(); int offset = getOffsetForPosition(x, y); final ClickableSpan[] links = mTextStorage.getSpans(offset, offset, ClickableSpan.class); if (links.length > 0) { links[0].onClick(this); return true; } } return super.onTouchEvent(event); // switch (event.getAction()) { // case MotionEvent.ACTION_UP: // // int x = (int) event.getX(); // int y = (int) event.getY(); // int offset = getOffsetForPosition(x, y); // // final ClickableSpan[] links = mTextStorage.getSpans(offset, offset, ClickableSpan.class); // // if (links.length > 0) { // links[0].onClick(this); // return true; // } // break; // } // // return true; }
private SpannableString getClickableSpan(final String name, final String uid) { SpannableString spannableString = new SpannableString(name); spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#232121")), 0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); spannableString.setSpan(new ClickableSpan() { @Override public void onClick(View widget) { if (mCommentItemClickListener != null) { LogUtil.e("点击了评论的belong用户"); mCommentItemClickListener.onCommentItemNameClick(uid); } } }, 0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); return spannableString; }
private SpannableString getClickableSpan(final String uid) { User user; if (uid.equals(UserManager.getInstance().getCurrentUserObjectId())) { user = UserManager.getInstance().getCurrentUser(); } else { user = UserCacheManager.getInstance().getUser(uid); } SpannableString spannableString = new SpannableString(user.getUsername()); spannableString.setSpan(new ClickableSpan() { @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); ds.setColor(defaultBgColor); ds.setUnderlineText(false); ds.clearShadowLayer(); } @Override public void onClick(View widget) { if (listener != null) { listener.onItemTextClick(uid); } } } , 0, user.getUsername().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); return spannableString; }
@Override public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_UP) { int x = (int) event.getX(); int y = (int) event.getY(); x -= widget.getTotalPaddingLeft(); y -= widget.getTotalPaddingTop(); x += widget.getScrollX(); y += widget.getScrollY(); Layout layout = widget.getLayout(); int line = layout.getLineForVertical(y); int off = layout.getOffsetForHorizontal(line, x); ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class); if (link.length != 0) { link[0].onClick(widget); } } return super.onTouchEvent(widget, buffer, event); }