aboutsummaryrefslogtreecommitdiff
path: root/WordPress/src/main/java/org/wordpress/android/util/WPLinkMovementMethod.java
blob: f7069be7e8480f0939c0fa27b4f95c3954efcfd8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package org.wordpress.android.util;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.URLSpan;
import android.view.MotionEvent;
import android.widget.TextView;

import org.wordpress.android.R;

/**
 * Android's LinkMovementMethod crashes on malformed links, including links that have no
 * protocol (ex: "example.com" instead of "http://example.com"). This class extends
 * LinkMovementMethod to catch and ignore the exception.
 */

public class WPLinkMovementMethod extends LinkMovementMethod {
    protected static WPLinkMovementMethod mMovementMethod;

    public static WPLinkMovementMethod getInstance() {
        if (mMovementMethod == null)
            mMovementMethod = new WPLinkMovementMethod();
        return mMovementMethod;
    }

    @Override
    public boolean onTouchEvent(TextView textView, Spannable buffer, MotionEvent event) {
        try {
            return super.onTouchEvent(textView, buffer, event) ;
        } catch (ActivityNotFoundException e) {
            AppLog.e(AppLog.T.UTILS, e);
            // attempt to correct the tapped url then launch the intent to display it
            showTappedUrl(textView.getContext(), fixTappedUrl(buffer));
            return true;
        }
    }

    private static String fixTappedUrl(Spannable buffer) {
        if (buffer == null)
            return null;

        URLSpan urlSpans[] = buffer.getSpans(0, buffer.length(), URLSpan.class);
        if (urlSpans.length == 0)
            return null;

        // note that there will be only one URLSpan (the one that was tapped)
        String url = StringUtils.notNullStr(urlSpans[0].getURL());
        if (Uri.parse(url).getScheme() == null)
            return "http://" + url.trim();

        return url.trim();
    }

    private static void showTappedUrl(Context context, String url) {
        if (context == null || TextUtils.isEmpty(url))
            return;
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            String readerToastUrlErrorIntent = context.getString(R.string.reader_toast_err_url_intent);
            ToastUtils.showToast(context, String.format(readerToastUrlErrorIntent, url), ToastUtils.Duration.LONG);
        }
    }
}