下面列出了怎么用android.text.util.Linkify的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Returns a new TextLinksParams object based on the specified link mask.
*
* @param mask the link mask
* e.g. {@link LinkifyMask#PHONE_NUMBERS} | {@link LinkifyMask#EMAIL_ADDRESSES}
* @hide
*/
@NonNull
public static TextLinksParams fromLinkMask(@LinkifyMask int mask) {
final List<String> entitiesToFind = new ArrayList<>();
if ((mask & Linkify.WEB_URLS) != 0) {
entitiesToFind.add(TextClassifier.TYPE_URL);
}
if ((mask & Linkify.EMAIL_ADDRESSES) != 0) {
entitiesToFind.add(TextClassifier.TYPE_EMAIL);
}
if ((mask & Linkify.PHONE_NUMBERS) != 0) {
entitiesToFind.add(TextClassifier.TYPE_PHONE);
}
if ((mask & Linkify.MAP_ADDRESSES) != 0) {
entitiesToFind.add(TextClassifier.TYPE_ADDRESS);
}
return new TextLinksParams.Builder().setEntityConfig(
TextClassifier.EntityConfig.createWithExplicitEntityList(entitiesToFind))
.build();
}
/** Returns a new options object based on the specified link mask. */
public static Options fromLinkMask(@LinkifyMask int mask) {
final List<String> entitiesToFind = new ArrayList<>();
if ((mask & Linkify.WEB_URLS) != 0) {
entitiesToFind.add(TextClassifier.TYPE_URL);
}
if ((mask & Linkify.EMAIL_ADDRESSES) != 0) {
entitiesToFind.add(TextClassifier.TYPE_EMAIL);
}
if ((mask & Linkify.PHONE_NUMBERS) != 0) {
entitiesToFind.add(TextClassifier.TYPE_PHONE);
}
if ((mask & Linkify.MAP_ADDRESSES) != 0) {
entitiesToFind.add(TextClassifier.TYPE_ADDRESS);
}
return new Options().setEntityConfig(
TextClassifier.EntityConfig.createWithEntityList(entitiesToFind));
}
@Override
public CharSequence getTransformation(CharSequence source, View view) {
if (view instanceof TextView) {
TextView textView = (TextView) view;
Linkify.addLinks(textView, Linkify.WEB_URLS);
if (textView.getText() == null || !(textView.getText() instanceof Spannable)) {
return source;
}
Spannable text = (Spannable) textView.getText();
URLSpan[] spans = text.getSpans(0, textView.length(), URLSpan.class);
for (int i = spans.length - 1; i >= 0; i--) {
URLSpan oldSpan = spans[i];
int start = text.getSpanStart(oldSpan);
int end = text.getSpanEnd(oldSpan);
String url = oldSpan.getURL();
text.removeSpan(oldSpan);
text.setSpan(new CustomTabsURLSpan(activity, url), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return text;
}
return source;
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
((YourLocalWeather) getApplication()).applyTheme(this);
super.onCreate(savedInstanceState);
applicationLocale = new Locale(PreferenceUtil.getLanguage(this));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
}
setContentView(R.layout.activity_voice_language_options);
setupActionBar();
TextView appLang = findViewById(R.id.pref_title_tts_lang_app_locale_id);
appLang.setText(getString(R.string.pref_title_tts_lang_app_locale) + " " + applicationLocale.getDisplayName());
TextView ttsAppGeneralInfo = findViewById(R.id.pref_title_tts_app_general_info_id);
Linkify.addLinks(ttsAppGeneralInfo, Linkify.WEB_URLS);
voiceSettingParametersDbHelper = VoiceSettingParametersDbHelper.getInstance(this);
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
final int id = item.getItemId();
if (id == R.id.action_github) {
Intents.openUrl(MainActivity.this, "https://github.com/boybeak/BeMusic");
} else if (id == R.id.action_star_me) {
Intents.viewMyAppOnStore(MainActivity.this);
} else if (id == R.id.action_help) {
final String message = getString(R.string.text_help);
TextView messageTv = new TextView(MainActivity.this);
final int padding = (int)(getResources().getDisplayMetrics().density * 24);
messageTv.setPadding(padding, padding, padding, padding);
messageTv.setAutoLinkMask(Linkify.WEB_URLS);
messageTv.setText(message);
new AlertDialog.Builder(MainActivity.this)
.setTitle(R.string.title_menu_help)
.setView(messageTv)
.setPositiveButton(android.R.string.ok, null)
.show();
}
mDrawerLayout.closeDrawers();
return true;
}
private void listing6_12() {
// Listing 6-12: Creating custom link strings in Linkify
// Define the base URI.
String baseUri = "content://com.paad.earthquake/earthquakes/";
// Construct an Intent to test if there is an Activity capable of
// viewing the content you are Linkifying. Use the Package Manager
// to perform the test.
PackageManager pm = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(baseUri));
boolean activityExists = testIntent.resolveActivity(pm) != null;
// If there is an Activity capable of viewing the content
// Linkify the text.
if (activityExists) {
int flags = Pattern.CASE_INSENSITIVE;
Pattern p = Pattern.compile("\\bquake[\\s]?[0-9]+\\b", flags);
Linkify.addLinks(myTextView, p, baseUri);
}
}
protected MenuTextView createTextView() {
Context activity = getGDActivity();
MenuTextView textView = new MenuTextView(activity);
textView.setText(spanned);
textView.setTextColor(TEXT_COLOR);
textView.setTextSize(TEXT_SIZE);
textView.setLineSpacing(0f, 1.5f);
textView.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
));
Linkify.addLinks(textView, Linkify.WEB_URLS);
textView.setLinksClickable(true);
return textView;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == 888) {
String result = data.getExtras().getString("result");
if (TextUtils.isEmpty(result)) {
RLUiUtil.toast(this, R.string.scan_retry);
return;
}
RLAlertDialog dialog = new RLAlertDialog(this, getString(R.string.scan_result), result, Linkify.ALL,
getString(android.R.string.yes), getString(android.R.string.cancel), new RLAlertDialog.Listener() {
@Override
public void onLeftClick() {}
@Override
public void onRightClick() {}
});
dialog.show();
}
}
/**
* <<<<<<< e370c9bc00e8f6b33b1d12a44b4c70a7f063c8b9
* Parses Spanned text for existing html links and reapplies them after the text has been Linkified
* =======
* Parses Spanned text for existing html links and reapplies them.
* >>>>>>> Issue #168 bugfix for links not being clickable, adds autoLink feature including web, phone, map and email
*
* @param spann {@link Spanned} text which has to be Linkified
* @param mask bitmask to define which kinds of links will be searched and applied (e.g. <a href="https://developer.android.com/reference/android/text/util/Linkify.html#ALL">Linkify.ALL</a>)
* @return Linkified {@link Spanned} text
* @see <a href="https://developer.android.com/reference/android/text/util/Linkify.html">Linkify</a>
*/
public static Spanned linkifySpanned(@NonNull final Spanned spann, final int mask) {
URLSpan[] existingSpans = spann.getSpans(0, spann.length(), URLSpan.class);
List<Pair<Integer, Integer>> links = new ArrayList<>();
for (URLSpan urlSpan : existingSpans) {
links.add(new Pair<>(spann.getSpanStart(urlSpan), spann.getSpanEnd(urlSpan)));
}
Linkify.addLinks((Spannable) spann, mask);
// add the links back in
for (int i = 0; i < existingSpans.length; i++) {
((Spannable) spann).setSpan(existingSpans[i], links.get(i).first, links.get(i).second, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return spann;
}
/**
* 显示项目信息
*/
private void displayAboutDialog() {
final int paddingSizeDp = 5;
final float scale = getResources().getDisplayMetrics().density;
final int dpAsPixels = (int) (paddingSizeDp * scale + 0.5f);
final TextView textView = new TextView(this);
final SpannableString text = new SpannableString(getString(R.string.about_dialog_text));
textView.setText(text);
textView.setAutoLinkMask(RESULT_OK);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setPadding(dpAsPixels, dpAsPixels, dpAsPixels, dpAsPixels);
Linkify.addLinks(text, Linkify.ALL);
new AlertDialog.Builder(this).setTitle(R.string.menu_about).setCancelable(false).setPositiveButton(android.R
.string.ok, null)
.setView(textView).show();
}
public static Spannable formatURLSpan(Spannable s) {
Linkify.addLinks(s, Linkify.WEB_URLS);
URLSpan[] urlSpans = s.getSpans(0, s.length(), URLSpan.class);
for (URLSpan urlSpan : urlSpans) {
final String url = urlSpan.getURL();
final Matcher m = chinesePattern.matcher(url);
if (m.find()) {
s.removeSpan(urlSpan);
continue;
}
int start = s.getSpanStart(urlSpan);
int end = s.getSpanEnd(urlSpan);
s.removeSpan(urlSpan);
s.setSpan(new TalkURLSpan(urlSpan.getURL(), ThemeUtil.getThemeColor(MainApp.CONTEXT.
getResources(), BizLogic.getTeamColor())), start, end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return s;
}
public void open(){
SpannableString str = new SpannableString("Copyright © : TWOh's Engineering " +
"\nTutorial lengkap di http://www.twoh.co/mudengdroid-belajar-android-bersama-twohs-engineering/android-design-tutorial/");
LinkifyCompat.addLinks(str, Linkify.WEB_URLS);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage(str);
alertDialogBuilder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
arg0.dismiss();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
public OutdatedReminder(@NonNull final Context context) {
super(context.getString(R.string.info_outdated_app_title),
context.getString(R.string.info_outdated_app_text));
setOkListener(v -> {
AlertDialog sourceDialog = new AlertDialog.Builder(context)
.setTitle(R.string.info_outdated_app_dialog_title)
.setMessage(context.getString(R.string.info_outdated_app_dialog_text)
+"\n\nF-Droid: https://f-droid.org/packages/com.b44t.messenger"
+"\n\nGoogle Play: https://play.google.com/store/apps/details?id=chat.delta")
.setPositiveButton(R.string.ok, (dialog, which) -> dialog.cancel())
.create();
sourceDialog.show();
Linkify.addLinks((TextView) Objects.requireNonNull(sourceDialog.findViewById(android.R.id.message)), Linkify.WEB_URLS);
});
}
@Override
public BaseDialogFragment.Builder build(BaseDialogFragment.Builder builder) {
TextView message = new TextView(getActivity());
message.setText(getString(R.string.login_error));
Linkify.addLinks(message, Linkify.ALL);
int padding = (int) getActivity().getResources()
.getDimension(R.dimen.dialog_message_padding);
builder.setView(message, padding, padding, padding, padding);
builder.setTitle(getString(R.string.hmm));
builder.setNegativeButton(getString(android.R.string.ok), new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
return builder;
}
private void presentResultDialog(@NonNull String url) {
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(R.string.SubmitDebugLogActivity_success)
.setCancelable(false)
.setNeutralButton(R.string.SubmitDebugLogActivity_ok, (d, w) -> finish())
.setPositiveButton(R.string.SubmitDebugLogActivity_share, (d, w) -> {
ShareCompat.IntentBuilder.from(this)
.setText(url)
.setType("text/plain")
.setEmailTo(new String[] { "[email protected]" })
.startChooser();
});
TextView textView = new TextView(builder.getContext());
textView.setText(getResources().getString(R.string.SubmitDebugLogActivity_copy_this_url_and_add_it_to_your_issue, url));
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setOnLongClickListener(v -> {
Util.copyToClipboard(this, url);
Toast.makeText(this, R.string.SubmitDebugLogActivity_copied_to_clipboard, Toast.LENGTH_SHORT).show();
return true;
});
LinkifyCompat.addLinks(textView, Linkify.WEB_URLS);
ViewUtil.setPadding(textView, (int) ThemeUtil.getThemedDimen(this, R.attr.dialogPreferredPadding));
builder.setView(textView);
builder.show();
}
@Test
public void testSpannable() {
final Spannable text = new SpannableString("Test http://www.test.de !");
Linkify.addLinks(text, Linkify.WEB_URLS);
assertEquals(
"<p dir=\"ltr\">Test <a href=\"http://www.test.de\">http://www.test.de</a> !</p>\n",
Html.toHtml(text));
}
@Override
public void generateDialog(LinearLayout layout) {
Context context = layout.getContext();
l = new TextView(context);
l.setId(View.generateViewId());
l.setAutoLinkMask(Linkify.ALL);
if(textLabel != null)
l.setText(textLabel);
else
l.setText(label);
layout.addView(l);
}
private static void addLinks(
TextLinks.Builder links, String string, @EntityType String entityType) {
final Spannable spannable = new SpannableString(string);
if (Linkify.addLinks(spannable, linkMask(entityType))) {
final URLSpan[] spans = spannable.getSpans(0, spannable.length(), URLSpan.class);
for (URLSpan urlSpan : spans) {
links.addLink(
spannable.getSpanStart(urlSpan),
spannable.getSpanEnd(urlSpan),
entityScores(entityType),
urlSpan);
}
}
}
@LinkifyMask
private static int linkMask(@EntityType String entityType) {
switch (entityType) {
case TextClassifier.TYPE_URL:
return Linkify.WEB_URLS;
case TextClassifier.TYPE_PHONE:
return Linkify.PHONE_NUMBERS;
case TextClassifier.TYPE_EMAIL:
return Linkify.EMAIL_ADDRESSES;
default:
// NOTE: Do not support MAP_ADDRESSES. Legacy version does not work well.
return 0;
}
}
private SelectionResult performClassification(@Nullable TextSelection selection) {
if (!Objects.equals(mText, mLastClassificationText)
|| mSelectionStart != mLastClassificationSelectionStart
|| mSelectionEnd != mLastClassificationSelectionEnd
|| !Objects.equals(mDefaultLocales, mLastClassificationLocales)) {
mLastClassificationText = mText;
mLastClassificationSelectionStart = mSelectionStart;
mLastClassificationSelectionEnd = mSelectionEnd;
mLastClassificationLocales = mDefaultLocales;
trimText();
final TextClassification classification;
if (Linkify.containsUnsupportedCharacters(mText)) {
// Do not show smart actions for text containing unsupported characters.
android.util.EventLog.writeEvent(0x534e4554, "116321860", -1, "");
classification = TextClassification.EMPTY;
} else if (mContext.getApplicationInfo().targetSdkVersion
>= Build.VERSION_CODES.P) {
final TextClassification.Request request =
new TextClassification.Request.Builder(
mTrimmedText, mRelativeStart, mRelativeEnd)
.setDefaultLocales(mDefaultLocales)
.build();
classification = mTextClassifier.get().classifyText(request);
} else {
// Use old APIs.
classification = mTextClassifier.get().classifyText(
mTrimmedText, mRelativeStart, mRelativeEnd, mDefaultLocales);
}
mLastClassificationResult = new SelectionResult(
mSelectionStart, mSelectionEnd, classification, selection);
}
return mLastClassificationResult;
}
public static Uri parseURL(String str) {
if (str == null || str.isEmpty())
return null;
Spannable spannable = new SpannableString(str);
Linkify.addLinks(spannable, Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES);
URLSpan[] spans = spannable.getSpans(0, spannable.length(), URLSpan.class);
return (spans.length > 0) ? Uri.parse(spans[0].getURL()) : null;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(
R.layout.open_listitem, null);
}
TextView link = (TextView) convertView.findViewById(R.id.open_list_item_link);
link.setAutoLinkMask(Linkify.WEB_URLS);
switch (position){
case 0:
link.setText("https://github.com/zym2014/MingQQ");
break;
case 1:
link.setText("https://github.com/neokree/MaterialTabs");
break;
case 2:
link.setText("https://github.com/afollestad/material-dialogs");
break;
case 3:
link.setText("https://github.com/kyleduo/SwitchButton");
break;
case 4:
link.setText("https://github.com/keithellis/MaterialWidget");
break;
case 5:
link.setText("https://github.com/baoyongzhang/android-PullRefreshLayout");
break;
case 6:
link.setText("https://github.com/ikew0ng/SwipeBackLayout");
break;
case 7:
link.setText("https://github.com/wang4yu6peng13/MaterialQQLite");
break;
}
TextView text = (TextView) convertView.findViewById(R.id.open_list_item); //设置条目的文字说明
text.setText(open_list.get(position));
return convertView;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.aboutus, container, false);
getActivity().setTitle("About us");
textView = view.findViewById(R.id.txtv);
Linkify.addLinks(textView, Linkify.ALL);
return view;
}
/**
* Generate text and put in @ref{about_text}
* @param about_text Resource it of destination TextView
*/
@SuppressWarnings("StringConcatenationInsideStringBufferAppend")
public void toTextView(@IdRes int about_text) {
TextView out = (TextView) activity.findViewById(about_text);
out.setAutoLinkMask(Linkify.WEB_URLS);
endYear = endYear();
StringBuilder sb = new StringBuilder();
if (appName != null)
sb.append(appName+" v"+getVersionString()+"\n");
if (copyright != null) {
sb.append("Copyright (c) ");
if (year != 0)
sb.append(year + (endYear != 0 ? " - " + endYear : "") + " ");
sb.append(copyright + "\n\n");
}
if (description != null)
sb.append(description+"\n\n");
// Sort library list alphabetically by name
Collections.sort(libs, new Comparator<Lib>() {
@Override
public int compare(Lib lhs, Lib rhs) {
return lhs.name.compareTo(rhs.name);
}
});
for(Lib l:libs){
sb.append(l.byLine() + "\n");
}
out.setText(sb.toString());
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View customView = getActivity().getLayoutInflater().inflate(R.layout.blur_dialog_dialog_fragment, null);
TextView label = ((TextView) customView.findViewById(R.id.textView));
label.setMovementMethod(LinkMovementMethod.getInstance());
Linkify.addLinks(label, Linkify.WEB_URLS);
builder.setView(customView);
return builder.create();
}
/**
* Show a model dialog box. The <code>android.app.AlertDialog</code> object is returned so that
* you can specify an OnDismissListener (or other listeners) if required.
* <b>Note:</b> show() is already called on the AlertDialog being returned.
*
* @param context The current Context or Activity that this method is called from.
* @param message Message to display in the dialog.
* @return AlertDialog that is being displayed.
*/
public static AlertDialog quickDialog(final Activity context, final String message) {
final SpannableString s = new SpannableString(message); //Make links clickable
Linkify.addLinks(s, Linkify.ALL);
Builder builder = new AlertDialog.Builder(context);
builder.setMessage(s);
builder.setPositiveButton(android.R.string.ok, closeDialogListener());
AlertDialog dialog = builder.create();
dialog.show();
((TextView) dialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance()); //Make links clickable
return dialog;
}
private void userActivateCodec(final Map<String, Object> codec, boolean activate) {
String codecName = (String) codec.get(CODEC_ID);
final short newPrio = activate ? (short) 1 : (short) 0;
boolean isDisabled = ((Short) codec.get(CODEC_PRIORITY) == 0);
if(isDisabled == !activate) {
// Nothing to do, this codec is already enabled
return;
}
if(NON_FREE_CODECS.containsKey(codecName) && activate) {
final TextView message = new TextView(getActivity());
final SpannableString s = new SpannableString(getString(R.string.this_codec_is_not_free) + NON_FREE_CODECS.get(codecName));
Linkify.addLinks(s, Linkify.WEB_URLS);
message.setText(s);
message.setMovementMethod(LinkMovementMethod.getInstance());
message.setPadding(10, 10, 10, 10);
//Alert user that we will disable for all incoming calls as he want to quit
new AlertDialog.Builder(getActivity())
.setTitle(R.string.warning)
.setView(message)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
setCodecActivated(codec, newPrio);
}
})
.setNegativeButton(R.string.cancel, null)
.show();
}else {
setCodecActivated(codec, newPrio);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_search_query);
Intent intent = getIntent();
String queryText = intent.getStringExtra(QUERY);
if (queryText != null) {
TextView txtMsg = (TextView)findViewById(R.id.txtMsg);
txtMsg.setText(queryText);
Linkify.addLinks(txtMsg, Linkify.ALL);
}
}
private static void linkifyUrl(Spannable spannable) {
Linkify.TransformFilter transformFilter = new Linkify.TransformFilter() {
@Override
public String transformUrl(Matcher matcher, String value) {
return value;
}
};
Linkify.addLinks(spannable, PATTERN_URL, SCHEME_URL, null, transformFilter);
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView view = (TextView) findViewById(R.id.textview);
Linkify.addLinks(view, Linkify.WEB_URLS| Linkify.EMAIL_ADDRESSES);
}