Created
May 22, 2015 05:38
-
-
Save rafaeltoledo/0d29d4b937968cdadf33 to your computer and use it in GitHub Desktop.
Intercept Autolinks in 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
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" | |
android:layout_width="match_parent" | |
android:layout_height="match_parent"> | |
<TextView | |
android:id="@+id/text" | |
android:layout_width="wrap_content" | |
android:layout_height="wrap_content" | |
android:autoLink="web" | |
android:clickable="true" | |
android:linksClickable="true" | |
android:text="This text must contain not only a link http://www.google.com but some more text and another link http://twitter.com" /> | |
</RelativeLayout> |
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 net.rafaeltoledo.autolinks; | |
import android.net.Uri; | |
import android.os.Bundle; | |
import android.support.annotation.NonNull; | |
import android.support.v7.app.AppCompatActivity; | |
import android.text.SpannableString; | |
import android.text.style.URLSpan; | |
import android.util.Log; | |
import android.view.View; | |
import android.widget.TextView; | |
public class MainActivity extends AppCompatActivity { | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
TextView text = (TextView) findViewById(R.id.text); | |
SpannableString current = (SpannableString) text.getText(); | |
URLSpan[] spans = current.getSpans(0, current.length(), URLSpan.class); | |
for (URLSpan span : spans) { | |
int start = current.getSpanStart(span); | |
int end = current.getSpanEnd(span); | |
current.removeSpan(span); | |
current.setSpan(new MyUrlSpan(span.getURL()), start, end, 0); | |
} | |
} | |
public static class MyUrlSpan extends URLSpan { | |
public MyUrlSpan(String url) { | |
super(url); | |
} | |
@Override | |
public void onClick(@NonNull View widget) { | |
Uri uri = Uri.parse(getURL()); | |
Log.d("URL", uri.toString()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment