Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we open TextView's links into Webview

Tags:

android

How can I open TextView's links into WebView when I click on links of TextView.

like image 395
Saki Make Avatar asked Aug 31 '11 09:08

Saki Make


2 Answers

Spanned spanned = Html.fromHtml("<a href=\"http://google.com\">google.com</a>");
textView.setText(spanned);

EDIT: That's not an ideal way to handle clicks on a link, but I don't know any other way.

Your main activity contains a TextView with a link. The link URL has a custom scheme.

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TextView link = (TextView)findViewById(R.id.link);
        link.setText(
            Html.fromHtml("<a href='myscheme://www.google.com'>link</a>"));
        link.setMovementMethod(LinkMovementMethod.getInstance());
    }
}

When this link is clicked Android starts an Activity with ACTION_VIEW using the link URL. Let's assume you have a WebViewActivity which handles URIs with this custom scheme. It gets the passed URI and replaces its scheme with http.

public class WebViewActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );

        if( savedInstanceState == null ) {
            String url =
                getIntent().getDataString().replace("myscheme://", "http://");
            // do something with this URL.
        }
    }
}

To handle custom URI schemes WebViewActivity must have an intent filter in the AndroidManifest.xml file:

<activity android:name=".WebViewActivity" android:exported="false">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:scheme="myscheme" />
    </intent-filter>
</activity>
like image 163
Michael Avatar answered Oct 21 '22 05:10

Michael


If you copy a Kotlin solution of nastylion, you can use it like:

textView.handleUrlClicks { url ->
    Timber.d("click on found span: $url")
    // Call WebView here.
}

Also you can see an article with its LinkMovementMethod and linkify, but it's too difficult (contains different masks and popup menus).

like image 35
CoolMind Avatar answered Oct 21 '22 04:10

CoolMind