How can I open TextView's links into WebView when I click on links of TextView.
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>
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With