1 /* 2 * Copyright (C) 2023 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.devicelockcontroller.activities.util; 18 19 import android.content.Context; 20 import android.content.Intent; 21 import android.text.Html; 22 import android.text.Spannable; 23 import android.text.SpannableString; 24 import android.text.method.LinkMovementMethod; 25 import android.text.style.ClickableSpan; 26 import android.text.style.URLSpan; 27 import android.view.View; 28 import android.widget.TextView; 29 30 import androidx.annotation.NonNull; 31 32 import com.android.devicelockcontroller.activities.HelpActivity; 33 34 /** 35 * A utility class which handles URL. 36 */ 37 public final class UrlUtils { 38 UrlUtils()39 private UrlUtils() {} 40 41 /** 42 * Sets a text on the given {@link TextView}. If the text contains URLs, the text will be 43 * formatted. 44 */ setUrlText(TextView textView, String text)45 public static void setUrlText(TextView textView, String text) { 46 SpannableString spannableString = 47 new SpannableString(Html.fromHtml(text, Html.FROM_HTML_MODE_COMPACT)); 48 if (handleUrlSpan(spannableString)) { 49 textView.setText(spannableString); 50 textView.setMovementMethod(LinkMovementMethod.getInstance()); 51 } else { 52 textView.setText(text); 53 } 54 } 55 handleUrlSpan(SpannableString text)56 private static boolean handleUrlSpan(SpannableString text) { 57 boolean hasUrl = false; 58 URLSpan[] spans = text.getSpans(0, text.length(), URLSpan.class); 59 for (URLSpan span : spans) { 60 int start = text.getSpanStart(span); 61 int end = text.getSpanEnd(span); 62 ClickableSpan clickableSpan = new CustomClickableSpan(span.getURL()); 63 text.removeSpan(span); 64 text.setSpan(clickableSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 65 hasUrl = true; 66 } 67 return hasUrl; 68 } 69 70 /** 71 * A {@link ClickableSpan} which will open the URL the text contains in the 72 * {@link HelpActivity}. 73 */ 74 private static final class CustomClickableSpan extends ClickableSpan { 75 final String mUrl; 76 CustomClickableSpan(String url)77 CustomClickableSpan(String url) { 78 mUrl = url; 79 } 80 81 @Override onClick(@onNull View view)82 public void onClick(@NonNull View view) { 83 Context context = view.getContext(); 84 Intent webIntent = new Intent(context, HelpActivity.class); 85 webIntent.putExtra(HelpActivity.EXTRA_URL_PARAM, mUrl); 86 context.startActivity(webIntent); 87 } 88 } 89 } 90