Last active
August 29, 2015 14:25
-
-
Save Atsumi3/027270297f37b9b75b66 to your computer and use it in GitHub Desktop.
TextView , 及びTextView を継承しているクラスにリンク付きのテキストをセットする
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package info.nukoneko.util; | |
import android.content.Context; | |
import android.support.annotation.NonNull; | |
import android.support.annotation.StringRes; | |
import android.text.SpannableString; | |
import android.text.Spanned; | |
import android.text.method.LinkMovementMethod; | |
import android.text.style.ClickableSpan; | |
import android.widget.TextView; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
public class TextLinkUtil { | |
public static SpannableString getLink( | |
@NonNull final Context context, | |
@StringRes int textID, | |
@StringRes int targetLinkTextID, | |
@NonNull ClickableSpan clickableSpan){ | |
return setLink(context,textID, targetLinkTextID, clickableSpan); | |
} | |
public static void getLink( | |
@NonNull final Context context, | |
@NonNull TextView view, | |
@StringRes int textID, | |
@StringRes int targetLinkTextID, | |
@NonNull ClickableSpan clickableSpan){ | |
view.setMovementMethod(LinkMovementMethod.getInstance()); | |
view.setText(setLink(context, textID, targetLinkTextID, clickableSpan)); | |
} | |
private static SpannableString setLink( | |
@NonNull final Context context, | |
@StringRes int textID, | |
@StringRes int targetLinkTextID, | |
@NonNull ClickableSpan clickableSpan){ | |
SpannableString builder = new SpannableString(context.getString(textID)); | |
Pattern p = Pattern.compile(context.getString(targetLinkTextID)); | |
Matcher linkText = p.matcher(context.getString(textID)); | |
while (linkText.find()){ | |
builder.setSpan( | |
clickableSpan, | |
linkText.start(), | |
linkText.end(), | |
Spanned.SPAN_INCLUSIVE_INCLUSIVE); | |
} | |
return builder; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment