I have a text view. In that I have text like this "You may visit this: http://www.google.com". After clicking this link it should open it in a webview instead of default browser. My code is:
//MainActivity.java
link = (TextView) findViewById(R.id.textView);
link.setText("You may visit here : http://www.google.com");
link.setMovementMethod(LinkMovementMethod.getInstance());
//Manifest
<activity
android:name="com.xpointers.xpmediaapp.mediaapp.WebViewActivity"
android:label="@string/app_name">
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.VIEW" />
</intent-filter>
</activity>
I tried using this link: handle textview link click in my android app but failed to understand and what should I write in WebviewActivity?
The following problems need to be solved:
Linkify the TextView Find a way to listen to a click on a link in the TextView Get the url of the clicked link and load it in the WebView Optional: make the TextView clickable without losing the ability to select text Optional: handle formatted text in the TextView (different text sizes and styles)
String text = "These are some sample links:\nwww.google.com\nwww.facebook.com\nwww.yahoo.com";
Spannable spannable = new SpannableString( Html.fromHtml(text) );
Linkify.addLinks(spannable, Linkify.WEB_URLS);
URLSpan[] spans = spannable.getSpans(0, spannable.length(), URLSpan.class);
for (URLSpan urlSpan : spans) {
LinkSpan linkSpan = new LinkSpan(urlSpan.getURL());
int spanStart = spannable.getSpanStart(urlSpan);
int spanEnd = spannable.getSpanEnd(urlSpan);
spannable.setSpan(linkSpan, spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.removeSpan(urlSpan);
}
For opening in new activity:
private class LinkSpan extends URLSpan {
private LinkSpan(String url) {
super(url);
}
@Override
public void onClick(View view) {
String url = getURL();
if (url != null) {
startActivity(new Intent(LinkTestActivity.this,WebViewActivity.class).putExtra("url",url));
}
}
}
And loding the url in webview.
for more see below link :-
Open URL in WebView instead of default Browser
As of the link you posted, you should declare in Manifest file that your certain activity can open links. When such link is clicked, your activity is opened, therefore you should set launch mode to singleTop. Then you can receive new intents and display them in your webview. onNewIntent: http://developer.android.com/reference/android/app/Activity.html#onNewIntent(android.content.Intent)
This example is about implementing search, so you can skip to the "singleTop" part: http://developer.android.com/guide/topics/search/search-dialog.html
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