1 /* 2 * Copyright (C) 2015 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.settings; 18 19 import android.text.Spannable; 20 import android.text.TextPaint; 21 import android.text.method.LinkMovementMethod; 22 import android.text.style.ClickableSpan; 23 import android.view.View; 24 import android.widget.TextView; 25 import android.widget.TextView.BufferType; 26 27 /** 28 * Utility class to create clickable links inside {@link TextView TextViews}. 29 */ 30 public class LinkifyUtils { 31 private static final String PLACE_HOLDER_LINK_BEGIN = "LINK_BEGIN"; 32 private static final String PLACE_HOLDER_LINK_END = "LINK_END"; 33 34 private LinkifyUtils() { 35 } 36 37 /** Interface that handles the click event of the link */ 38 public interface OnClickListener { 39 void onClick(); 40 } 41 42 /** 43 * Applies the text into the {@link TextView} and part of it a clickable link. 44 * The text surrounded with "LINK_BEGIN" and "LINK_END" will become a clickable link. Only 45 * supports at most one link. 46 * @return true if the link has been successfully applied, or false if the original text 47 * contains no link place holders. 48 */ 49 public static boolean linkify(TextView textView, StringBuilder text, 50 final OnClickListener listener) { 51 // Remove place-holders from the string and record their positions 52 final int beginIndex = text.indexOf(PLACE_HOLDER_LINK_BEGIN); 53 if (beginIndex == -1) { 54 textView.setText(text); 55 return false; 56 } 57 text.delete(beginIndex, beginIndex + PLACE_HOLDER_LINK_BEGIN.length()); 58 final int endIndex = text.indexOf(PLACE_HOLDER_LINK_END); 59 if (endIndex == -1) { 60 textView.setText(text); 61 return false; 62 } 63 text.delete(endIndex, endIndex + PLACE_HOLDER_LINK_END.length()); 64 65 textView.setText(text.toString(), BufferType.SPANNABLE); 66 textView.setMovementMethod(LinkMovementMethod.getInstance()); 67 Spannable spannableContent = (Spannable) textView.getText(); 68 ClickableSpan spannableLink = new ClickableSpan() { 69 @Override 70 public void onClick(View widget) { 71 listener.onClick(); 72 } 73 74 @Override 75 public void updateDrawState(TextPaint ds) { 76 super.updateDrawState(ds); 77 ds.setUnderlineText(false); 78 } 79 }; 80 spannableContent.setSpan(spannableLink, beginIndex, endIndex, 81 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 82 return true; 83 } 84 } 85