Java Code Examples for android.text.style.ClickableSpan

The following are top voted examples for showing how to use android.text.style.ClickableSpan. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: AdaptiveTableLayout   File: CsvPickerFragment.java   Source Code and License 7 votes vote down vote up
@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);
}
 
Example 2
Project: Ghost-Android   File: AppUtils.java   Source Code and License 7 votes vote down vote up
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());
}
 
Example 3
Project: TYT   File: MessageCenterActivity.java   Source Code and License 6 votes vote down vote up
/**
 * 解析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;
}
 
Example 4
Project: Phoenix-for-VK   File: CommentsAdapter.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 5
Project: Nird2   File: UiUtils.java   Source Code and License 6 votes vote down vote up
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());
}
 
Example 6
Project: Nird2   File: UiUtils.java   Source Code and License 6 votes vote down vote up
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());
}
 
Example 7
Project: MainCalendar   File: AboutActivity.java   Source Code and License 6 votes vote down vote up
/**
     * 获取超链接字段
     * @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;
    }
 
Example 8
Project: chromium-for-android-56-debug-video   File: PermissionDialogController.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 9
Project: chromium-for-android-56-debug-video   File: PhysicalWebOptInActivity.java   Source Code and License 6 votes vote down vote up
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);
                }
            }));
}
 
Example 10
Project: chromium-for-android-56-debug-video   File: PassphraseTypeDialogFragment.java   Source Code and License 6 votes vote down vote up
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);
                }
            }));
}
 
Example 11
Project: chromium-for-android-56-debug-video   File: PassphraseDialogFragment.java   Source Code and License 6 votes vote down vote up
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);
                }
            }));
}
 
Example 12
Project: chromium-for-android-56-debug-video   File: UpdatePasswordInfoBar.java   Source Code and License 6 votes vote down vote up
@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]);
    }
}
 
Example 13
Project: chromium-for-android-56-debug-video   File: DuplicateDownloadInfoBar.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
        }
    });
}
 
Example 14
Project: chromium-for-android-56-debug-video   File: InfoBarLayout.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 15
Project: chromium-for-android-56-debug-video   File: AutofillSaveCardInfoBar.java   Source Code and License 6 votes vote down vote up
@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);
    }
}
 
Example 16
Project: chromium-for-android-56-debug-video   File: SearchGeolocationDisclosureInfoBar.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 17
Project: TagEditText   File: TagEditText.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 18
Project: mvvm-template   File: BetterLinkMovementExtended.java   Source Code and License 6 votes vote down vote up
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;
    }
}
 
Example 19
Project: FastTextView   File: ClickableSpanUtil.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 20
Project: OSchina_resources_android   File: RichTextParser.java   Source Code and License 6 votes vote down vote up
/**
 * 格式化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;
}
 
Example 21
Project: getword   File: GetWordTextView.java   Source Code and License 6 votes vote down vote up
/**
 * 重写点击事件
 * @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) {
        }
    };
}
 
Example 22
Project: Pocket-Plays-for-Twitch   File: ChatAdapter.java   Source Code and License 6 votes vote down vote up
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);
	}
}
 
Example 23
Project: Simpler   File: StatusDataSetter.java   Source Code and License 6 votes vote down vote up
/**
 * 微博文本触摸监听处理
 *
 * @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;
}
 
Example 24
Project: ShangHanLun   File: LittleTableViewWindow.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 25
Project: ShangHanLun   File: LittleTextViewWindow.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 26
Project: boohee_v5.6   File: LinkUtils.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 27
Project: Cable-Android   File: RegistrationProgressActivity.java   Source Code and License 6 votes vote down vote up
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());
}
 
Example 28
Project: Demos   File: TouchLinkMovementMethod.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 29
Project: GitHub   File: ClickableMovementMethod.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 30
Project: ExtraMapUtils   File: AppUtils.java   Source Code and License 5 votes vote down vote up
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;
        }
    });
}
 
Example 31
Project: ceji_android   File: ScrollingStrategy.java   Source Code and License 5 votes vote down vote up
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;		
}
 
Example 32
Project: CodeWatch   File: AboutActivity.java   Source Code and License 5 votes vote down vote up
@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));
}
 
Example 33
Project: Phoenix-for-VK   File: PrivacyAdapter.java   Source Code and License 5 votes vote down vote up
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();
            }
        }
    });
}
 
Example 34
Project: TurboChat   File: EspressoTestUtils.java   Source Code and License 5 votes vote down vote up
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();

        }
    };
}
 
Example 35
Project: godlibrary   File: SpannableUtils.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 36
Project: mongol-library   File: MongolTextView.java   Source Code and License 5 votes vote down vote up
@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;
    }
 
Example 37
Project: TestChat   File: CommentListView.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 38
Project: TestChat   File: LikerTextView.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 39
Project: Nird2   File: ArticleMovementMethod.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 40
Project: Nird2   File: ArticleMovementMethod.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 41
Project: SpanEZ   File: SpanEZ.java   Source Code and License 5 votes vote down vote up
@Override
public StyleEZ clickable(@NonNull Locator locator, @NonNull OnSpanClickListener spanClick) {
    for (TargetRange targetRange : locator.locate(content)) {
        ClickableSpan clickSpan = ClickableSpanEZ.from(spanClick,
                                                       content.substring(targetRange.getStart(),
                                                                         targetRange
                                                                                 .getEnd() + 1));
        target.setMovementMethod(new LinkMovementMethod());
        addSpan(targetRange, clickSpan);
    }
    return this;
}
 
Example 42
Project: SpanEZ   File: ClickableSpanEZTest.java   Source Code and License 5 votes vote down vote up
@Test
public void clicking_the_span_trigger_the_callback() {
    ClickableSpan clickableSpanEZ = ClickableSpanEZ.from(mockListener, FAKE_CONTENT);

    clickableSpanEZ.onClick(null);
    verify(mockListener, times(1)).onSpanClick(FAKE_CONTENT);
}
 
Example 43
Project: SpanEZ   File: SpanEZTest.java   Source Code and License 5 votes vote down vote up
@Test
public void click_should_add_only_one_span() {
    spanBuilder.clickable(range, spanClickListener)
               .apply();

    verify(mockTextView, times(1))
            .setMovementMethod(isA(LinkMovementMethod.class));

    verify((SpanEZ) spanBuilder, times(1))
            .addSpan(isA(TargetRange.class), isA(ClickableSpan.class));
}
 
Example 44
Project: SpanEZ   File: SpanEZTest.java   Source Code and License 5 votes vote down vote up
@Test
public void clicking_on_a_click_span_triggers_callback() {
    spanBuilder.clickable(range, spanClickListener)
               .apply();

    ArgumentCaptor<ClickableSpan> captor = ArgumentCaptor.forClass(ClickableSpan.class);
    verify((SpanEZ) spanBuilder, times(1))
            .addSpan(isA(TargetRange.class), captor.capture());

    captor.getValue().onClick(mockTextView);

    verify(spanClickListener, only())
            .onSpanClick(anyString());
}
 
Example 45
Project: orgzly-android   File: TextViewWithLinks.java   Source Code and License 5 votes vote down vote up
@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
    if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, event);

    Layout layout = this.getLayout();

    if (layout != null) {
        int line = layout.getLineForVertical((int) event.getY() - getTotalPaddingTop());
        int offset = getOffsetForPosition(event.getX(), event.getY());

        if (isEventOnText(event, layout, line) && getText() != null && getText() instanceof Spanned) {
            Spanned spanned = (Spanned) getText();

            ClickableSpan[] links = spanned.getSpans(offset, offset, ClickableSpan.class);

            if (links.length > 0) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    return true;

                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    links[0].onClick(this);

                } else {
                    return super.onTouchEvent(event);
                }
            }
        }
    }

    return super.onTouchEvent(event);
}
 
Example 46
Project: NovelReader   File: BookTextView.java   Source Code and License 5 votes vote down vote up
@Override
public void setText(CharSequence text, BufferType type) {
    String value = text.toString();
    int indexStart = 0;
    int indexEnd = 0;

    indexStart = value.indexOf("《",indexStart);
    indexEnd = value.indexOf("》",indexEnd);
    SpannableStringBuilder builder = new SpannableStringBuilder(value);
    while(indexStart != -1 || indexEnd != -1){
        final int start = indexStart+1;
        final int end = indexEnd;
        builder.setSpan(new ForegroundColorSpan(bookColor),indexStart,indexEnd+1,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        builder.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {

                if (mBookListener != null){
                    String bookName = value.substring(start,end);
                    mBookListener.onBookClick(bookName);
                }
            }
        }, indexStart, indexEnd+1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        indexStart = value.indexOf("《",indexStart+1);
        indexEnd = value.indexOf("》",indexEnd+1);
    }
    this.setMovementMethod(LinkMovementMethod.getInstance());
    super.setText(builder, type);
}
 
Example 47
Project: chromium-for-android-56-debug-video   File: AccountChooserDialog.java   Source Code and License 5 votes vote down vote up
private void show() {
    View titleView =
            LayoutInflater.from(mContext).inflate(R.layout.account_chooser_dialog_title, null);
    TextView origin = (TextView) titleView.findViewById(R.id.origin);
    origin.setText(mOrigin);
    TextView titleMessageText = (TextView) titleView.findViewById(R.id.title);
    if (mTitleLinkStart != 0 && mTitleLinkEnd != 0) {
        SpannableString spanableTitle = new SpannableString(mTitle);
        spanableTitle.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View view) {
                nativeOnLinkClicked(mNativeAccountChooserDialog);
                mDialog.dismiss();
            }
        }, mTitleLinkStart, mTitleLinkEnd, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        titleMessageText.setText(spanableTitle, TextView.BufferType.SPANNABLE);
        titleMessageText.setMovementMethod(LinkMovementMethod.getInstance());
    } else {
        titleMessageText.setText(mTitle);
    }
    mAdapter = generateAccountsArrayAdapter(mContext, mCredentials);
    final AlertDialog.Builder builder =
            new AlertDialog.Builder(mContext, R.style.AlertDialogTheme)
                    .setCustomTitle(titleView)
                    .setNegativeButton(R.string.cancel, this)
                    .setAdapter(mAdapter, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int item) {
                            mCredential = mCredentials[item];
                        }
                    });
    if (!TextUtils.isEmpty(mSigninButtonText)) {
        builder.setPositiveButton(mSigninButtonText, this);
    }
    mDialog = builder.create();
    mDialog.setOnDismissListener(this);
    mDialog.show();
}
 
Example 48
Project: chromium-for-android-56-debug-video   File: PassphraseCreationDialogFragment.java   Source Code and License 5 votes vote down vote up
private SpannableString getInstructionsText() {
    final Activity activity = getActivity();
    return SpanApplier.applySpans(
            activity.getString(R.string.sync_custom_passphrase),
            new SpanInfo("<learnmore>", "</learnmore>", new ClickableSpan() {
                @Override
                public void onClick(View view) {
                    HelpAndFeedback.getInstance(activity).show(activity,
                            activity.getString(R.string.help_context_change_sync_passphrase),
                            Profile.getLastUsedProfile(), null);
                }
            }));
}
 
Example 49
Project: chromium-for-android-56-debug-video   File: TranslateInfoBar.java   Source Code and License 5 votes vote down vote up
/**
 * @return a formatted message with a link to {@code panelId}
 */
private CharSequence formatAfterTranslateInfoBarMessage(String statement, String linkText,
        final int panelId) {
    SpannableStringBuilder result = new SpannableStringBuilder();
    result.append(statement).append(" ");
    SpannableString formattedChange = new SpannableString(linkText);
    formattedChange.setSpan(new ClickableSpan() {
        @Override
        public void onClick(View view) {
            swapPanel(panelId);
        }
    }, 0, linkText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    result.append(formattedChange);
    return result;
}
 
Example 50
Project: chromium-for-android-56-debug-video   File: DuplicateDownloadInfoBar.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the infobar text for regular downloads.
 * @param context Context to be used.
 * @param template Template of the text to be displayed.
 */
private CharSequence getDownloadMessageText(final Context context, final String template) {
    final File file = new File(mFilePath);
    final Uri fileUri = Uri.fromFile(file);
    final String mimeType = getMimeTypeFromUri(fileUri);
    final String filename = file.getName();
    return getMessageText(template, filename, new ClickableSpan() {
        @Override
        public void onClick(View view) {
            DownloadUtils.openFile(file, mimeType, mIsIncognito);
        }
    });
}
 
Example 51
Project: chromium-for-android-56-debug-video   File: DuplicateDownloadInfoBar.java   Source Code and License 5 votes vote down vote up
/**
 * Helper method to get the text to be displayed on the infobar.
 * @param template Message template.
 * @param fileName Name of the file.
 * @param clickableSpan Action to perform when clicking on the file name.
 * @return message to be displayed on the infobar.
 */
private CharSequence getMessageText(final String template, final String fileName,
        final ClickableSpan clickableSpan) {
    final SpannableString formattedFilePath = new SpannableString(fileName);
    formattedFilePath.setSpan(new StyleSpan(Typeface.BOLD), 0, fileName.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    formattedFilePath.setSpan(clickableSpan, 0, fileName.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return TextUtils.expandTemplate(template, formattedFilePath);
}
 
Example 52
Project: chromium-for-android-56-debug-video   File: GeneratedPasswordSavedInfoBar.java   Source Code and License 5 votes vote down vote up
/**
 * Used to specify button layout and custom content. Makes infobar display a single button and
 * an inline link in the message.
 * @param layout Handles user interface for the infobar.
 */
@Override
public void createContent(InfoBarLayout layout) {
    layout.setButtons(mButtonLabel, null);
    SpannableString message = new SpannableString(mMessageText);
    message.setSpan(
            new ClickableSpan() {
                @Override
                public void onClick(View view) {
                    onLinkClicked();
                }
            }, mInlineLinkRangeStart, mInlineLinkRangeEnd, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
    layout.setMessage(message);
}
 
Example 53
Project: letv   File: StringUtils.java   Source Code and License 5 votes vote down vote up
public static SpannableString generateTvSpreadSpanText(String text1, String text2, ClickableSpan clickableSpan) {
    if (TextUtils.isEmpty(text1)) {
        text1 = "";
    }
    String str = text1;
    if (!TextUtils.isEmpty(text2)) {
        str = text1 + text2;
    }
    SpannableString spannableString = new SpannableString(str);
    if (clickableSpan != null) {
        spannableString.setSpan(clickableSpan, text1.length(), str.length(), 33);
    }
    return spannableString;
}
 
Example 54
Project: HutHelper   File: LoginActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void doBusiness() {
    SpannableString spannableString = new SpannableString("密码默认为身份证后六位(x小写) 忘记密码?");

    spannableString.setSpan(new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            Bundle bundle = new Bundle();
            bundle.putInt("type", WebViewActivity.TYPE_CHANGE_PWD);
            bundle.putString("title", "修改密码");
            bundle.putString("url", Constants.CHANGE_PWD);
            LoginActivity.this.startActivity(WebViewActivity.class, bundle);
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setColor(Color.parseColor("#ff8f8f8f"));
            ds.setUnderlineText(true);
        }
    }, 17, 22, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    tvMessage.setText(spannableString);
    tvMessage.setMovementMethod(LinkMovementMethod.getInstance());

    KeyBoardUtils.scrollLayoutAboveKeyBoard(context, rootView, tvMessage);

    SharedPreferences.Editor editor = getSharedPreferences("login_user", MODE_PRIVATE).edit();
    editor.putString("userId", "*");
    editor.apply();

    loginPresenter = new LoginPresenter(this, this);

}
 
Example 55
Project: TagEditText   File: TagEditTextTest.java   Source Code and License 5 votes vote down vote up
@Test
public void should_remove_tag_on_click() {
    // Given
    final String testValue = "This is a test value.";
    final String textToRemove = "test";
    final String expectedValue = "This is a value.";

    // When
    mTagEditText.setText(testValue);
    final ClickableSpan clickableSpan = (ClickableSpan) findSpanForString(textToRemove, ClickableSpan.class);
    clickableSpan.onClick(null);

    // Then
    assertEquals(expectedValue, mTagEditText.getText().toString().trim());
}
 
Example 56
Project: PSNine   File: LocalLinkMovementMethod.java   Source Code and License 5 votes vote down vote up
@Override
public boolean onTouchEvent(TextView widget, 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 -= 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 if (action == MotionEvent.ACTION_DOWN) {
                Selection.setSelection(buffer,
                        buffer.getSpanStart(link[0]),
                        buffer.getSpanEnd(link[0]));
            }

            return true;
        } else {
            Selection.removeSelection(buffer);
            Touch.onTouchEvent(widget, buffer, event);
            return false;
        }
    }
    return Touch.onTouchEvent(widget, buffer, event);
}
 
Example 57
Project: javaide   File: FormatTextView.java   Source Code and License 5 votes vote down vote up
@Override
public void setText(CharSequence text, BufferType type) {
    Spanned html = Html.fromHtml(text.toString());
    ClickableSpan[] spans = html.getSpans(0, html.length(), ClickableSpan.class);
    if (spans != null && spans.length > 0) {
        setMovementMethod(LinkMovementMethod.getInstance());
    }
    super.setText(html, type);
}
 
Example 58
Project: xifan   File: ClickLinkMovementMethod.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 59
Project: CXJPadProject   File: LinkMovementClickMethod.java   Source Code and License 5 votes vote down vote up
@Override
public boolean onTouchEvent(TextView widget, 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 -= 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) {
                if(System.currentTimeMillis() - lastClickTime < CLICK_DELAY){
                    link[0].onClick(widget);
                }
            } else if (action == MotionEvent.ACTION_DOWN) {
                Selection.setSelection(buffer,
                        buffer.getSpanStart(link[0]),
                        buffer.getSpanEnd(link[0]));
                lastClickTime = System.currentTimeMillis();
            }

            return true;
        } else {
            Selection.removeSelection(buffer);
        }
    }
    return super.onTouchEvent(widget, buffer, event);
}
 
Example 60
Project: mvvm-template   File: BetterLinkMovementExtended.java   Source Code and License 5 votes vote down vote up
static BetterLinkMovementExtended.ClickableSpanWithText ofSpan(TextView textView, ClickableSpan span) {
    Spanned s = (Spanned) textView.getText();
    String text;
    if (span instanceof URLSpan) {
        text = ((URLSpan) span).getURL();
    } else {
        int start = s.getSpanStart(span);
        int end = s.getSpanEnd(span);
        text = s.subSequence(start, end).toString();
    }
    return new BetterLinkMovementExtended.ClickableSpanWithText(span, text);
}