Skip to content

Instantly share code, notes, and snippets.

@inferjay
Forked from whitfin/LinkMovementMethod.java
Created August 18, 2014 12:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inferjay/0e621f649da2441822dd to your computer and use it in GitHub Desktop.
Save inferjay/0e621f649da2441822dd to your computer and use it in GitHub Desktop.
package com.zackehh.example;
import com.zackehh.example.MinimalBrowser;
import android.content.Context;
import android.content.Intent;
import android.text.Layout;
import android.text.Spannable;
import android.text.method.MovementMethod;
import android.text.style.URLSpan;
import android.view.MotionEvent;
import android.widget.TextView;
/**
* Implementation of LinkMovementMethod to allow the loading of
* a link clicked inside text inside an Android application
* without exiting to an external browser.
*
* @author Isaac Whitfield
* @version 25/08/2013
*/
public class LinkMovementMethod extends android.text.method.LinkMovementMethod {
// The context we pass to the method
private static Context movementContext;
// A new LinkMovementMethod
private static LinkMovementMethod linkMovementMethod = new LinkMovementMethod();
public static MovementMethod getInstance(Context c){
// Set the context
movementContext = c;
// Return this movement method
return linkMovementMethod;
}
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event){
// Get the event action
int action = event.getAction();
// If action has finished
if(action == MotionEvent.ACTION_UP) {
// Locate the area that was pressed
int x = (int) event.getX();
int y = (int) event.getY();
x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();
x += widget.getScrollX();
y += widget.getScrollY();
// Locate the URL text
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
// Find the URL that was pressed
URLSpan[] link = buffer.getSpans(off, off, URLSpan.class);
// If we've found a URL
if (link.length != 0) {
// Find the URL
String url = link[0].getURL();
// If it's a valid URL
if (url.contains("https") | url.contains("tel") | url.contains("mailto") | url.contains("http") | url.contains("https") | url.contains("www")){
// Open it in an instance of InlineBrowser
movementContext.startActivity(new Intent(movementContext, MinimalBrowser.class).putExtra("url", url));
}
// If we're here, something's wrong
return true;
}
}
return super.onTouchEvent(widget, buffer, event);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment