How to get url from linkify textview - android

I need to highlight weburl inside textview.
To achieve this I have added android:autoLink="web" attribute inside my textview xml.
If url is related to youtube video I need to play it inside youtube player activity in my app and for other types of urls i want it to open on web browser.
So How I detect which url is get click and find is it youtube link or not and perform redirection according to it.
Following are sample text which my text view holding
this is sample text you can find nice article over this link
www.example.com and there is nice video which explain here
www.youtube.com/xyzpqr furthere reading please download pdf from
here www.example.com/pdf/xyz
there are multiple links is present so need to detect that clicked link and preform action on selected link.

You Can Apply Listener on TextView and When Click is Detected use StartsWith Method in Android To Detect if url starts with you.(url of youtube ) if it matches do your youtube player stuff else perform redirection

Why don't you use setMouvementMethod() instead ?
Try this in your TextView:
<TextView
android:id="#+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text"/>
Then add this line in you Java class:
TextView myLink = (TextView) findViewById(R.id.myTextView);
myLink.setMovementMethod(LinkMovementMethod.getInstance());

Please try below attribute in your textview in xml file:
android:autoLink="all"
android:linksClickable="false"
android:textColorLink="#3393FF"
You can check URL using contains function.
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String URL = textView.getText().toString();
if (URL.contains("youtube") || URL.contains("youtu.be")) {
// then redirect to youtube
} else if (URL.contains("pdf")) {
// then redirect to pdf app
} else {
// then redirect to web
}
}
});
OR
you can use below Library and link : https://github.com/saket/Better-Link-Movement-Method
implementation 'me.saket:better-link-movement-method:2.2.0'
Try below code :
BetterLinkMovementMethod
.linkify(Linkify.ALL, textView)
.setOnLinkClickListener((textView, url) -> {
// Handle clicks.
if (url.contains("youtube") || url.contains("youtu.be")) {
// then redirect to youtube
} else if (url.contains("pdf")) {
// then redirect to pdf app
} else {
// then redirect to web
}
return true;
})
.setOnLinkLongClickListener((textView, url) -> {
// Handle long-clicks.
return true;
});

Related

Android web browser

please predecessors, Am creating a web browser homepage in android studio and want to be able to input URL from the same editText as that of my search.
have been able to take search and load google results, but URL still end up in searched instade of loading the URL website.
this is my codes.
EditText searchEditText = rootView.findViewById (R.id.searchEditText);
ImageButton searchBt = rootView.findViewById (R.id.searchBt);
searchBt.setOnClickListener (new View.OnClickListener ( ) {
#Override
public void onClick(View v) {
String searchQuery = searchBar.getText ().toString ();
if(URLUtil.isValidUrl (searchQuery)){
webView.loadUrl (searchQuery);
}else {
String searchURL = "https://www.google.com/search?q="+searchQuery;
webView.loadUrl (searchURL);
}
}
});
The problem is probably because your URL doesn't have https at the beginning.
Try using some other mechanism to determine if the URL is valid.
For example, use WEB_URL pattern in Patterns Class
Patterns.WEB_URL.matcher(potentialUrl).matches()

Android Appcelerator Get URL from remote URL in webview and open it in devices default browser or a new webview

My question is exactly the same as this one but for Android and not iOS.
Get URL from remote URL in webview and open it in safari
Anyone have an idea. I am creating a cross-platform app and I have used the Clayton's answer to get it to work for iOS with some tweaks to open with a controller. But when trying different methods on Android and it is not working. This is as close as I have gotten (which is what Aaron provided on that same page) and it is not quite right as it opens the remote web page in a new browser window as well in the apps webview:
$.floorView.addEventListener('load', function(e) {
if (e.url.indexOf("http") !== -1) {
// stop the event
e.bubble = false;
// stop the url from loading
$.floorView.stopLoading();
// open
Ti.Platform.openURL(e.url);
}
});
Thanks!
I'd listen to the beforeload event, although I'm not 100% sure if you can actually prevent the Webview from still continuing the load as well.
Another way would be to intercept these links via JS you load or inject (evalJS()) in the webpage. Then fire a Ti.App event and respond to it in Titanium.
The Titanium.UI.Webview has a specific property for intercepting links: onlink.
This is not implemented as an event because it is a callback and needs to return a boolean to tell the Webview whether or not to load the URL of the link.
Oddly, setting the onlink callback right away makes the URL immediately load in Safari, so I did it this way:
$.webview.addEventListener('load', function(e) {
$.webview.onlink = function(e) {
Ti.Platform.openURL(e.url);
return false;
};
});
You can of course check the e.url string and decide whether to open it internally or externally.
I think I may have figured it out. Thanks to those whose ideas and suggestions lead to this code.
It appears to be working as I want on iOS and Android. Any suggestions or issues that you guys have I would appreciate the feedback. Thanks!
if ("iOS") {
$.webView.addEventListener('beforeload', function(e) {
if (e.navigationType == Titanium.UI.iOS.WEBVIEW_NAVIGATIONTYPE_LINK_CLICKED) {
// stop the event
e.bubble = false;
// stop the url from loading
$.webView.stopLoading();
//opens up the clicked URL for bill in new webView
var link = e.url;
var args = {url: link,};
// open link in my default webView for iOS
var newWebView=Alloy.createController('defaultWebView', args).getView();
newWebView.open();
}
});
}
else if ("Android") {
$.webView.addEventListener('beforeload', function(e) {
if (e.url.indexOf("http") !== -1) {
function Parser(text) {
var html = text;
var urlRegex = /((http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?)/gi;
this.getHTML = function() {
return html;
};
} // end Parser
var parser = new Parser(e.url);
html = parser.getHTML();
if (html != "url of $.webView") {
// stop it from loding in current webView
$.webView.stopLoading();
// open link in browser
Ti.Platform.openURL(html);
}
}
});
}
else {
.....................
}

Getting "Link text" of the link displayed in WebView

I have Android WebView which displays some links as: Link1TextLink2Text Now I would like to retrieve Link1Text and Link2Text when I long press these links. I have contextMenu implemented in the code and I could successfully get the link urls (http://link1.html, http://link2.html) using HitTestResult getExtra() method but how ccan I get those link texts ?FYI, I require those link texts for implementing "Copy link text" option in the contextMenu.
To get the text of an achor link:
I. Hook a touchstart listener to every web pages in the onPageFinished() callback of WebViewClient via evaluateJavascript. like:
//Javascripts to evaluate in onPageFinished
const w=window;
w.addEventListener('touchstart',wrappedOnDownFunc);
function wrappedOnDownFunc(e){
if(e.touches.length==1){
w._touchtarget = e.touches[0].target;
}
console.log('hey touched something ' +w._touchtarget);
}
note we've saved the touch target.
II. Then implement OnLongClicklisenter for webview. use evaluateJavascript again when you long pressed on a link object:
#Override
public boolean onLongClick(View v) {
WebView.HitTestResult result = ((WebView)v).getHitTestResult();
if (null == result) return false;
int type = result.getType();
switch (type) {
case WebView.HitTestResult.SRC_ANCHOR_TYPE:
if(result.getExtra()!=null){
((WebView)v).evaluateJavascript("window._touchtarget?window._touchtarget.innerText:''", new ValueCallback<String>() {
#Override
public void onReceiveValue(String value) {
System.out.println("hey received link text : "+value);
}
});
}
return true;
}
return false;
}
What's more, we can even choose to select the text of the anchor element! Actually this is one of the options that samsung browser offers when you long-pressed an tag .
To achieve this, we still need that recorded touch target. Besides we need 2 new javascript methods:
function selectTouchtarget(){
var tt = w._touchtarget;
if(tt){
w._touchtarget_href = tt.getAttribute("href");
tt.removeAttribute("href");
var sel = w.getSelection();
var range = document.createRange();
range.selectNodeContents(tt);
sel.removeAllRanges();
sel.addRange(range);
}
}
function restoreTouchtarget(){
var tt = w._touchtarget;
if(tt){
tt.setAttribute("href", w._touchtarget_href);
}
}
Finnaly in the onLongClick listener, instead of just fetch the innerText, we programmatically set the selection, trigger the action menu bar, and restore the removed href attribute of our touch target.
case WebViewmy.HitTestResult.SRC_ANCHOR_TYPE:
if(result.getExtra()!=null){
WebViewmy mWebView = ((WebViewmy)v);
mWebView.evaluateJavascript("selectTouchtarget()", new ValueCallback<String>() {
#Override
public void onReceiveValue(String value) {
/* bring in action mode by a fake click on the programmatically selected text. */
MotionEvent te = MotionEvent.obtain(0,0,KeyEvent.ACTION_DOWN,mWebView.lastX,mWebView.lastY,0);
mWebView.dispatchTouchEvent(te);
te.setAction(KeyEvent.ACTION_UP);
mWebView.dispatchTouchEvent(te);
te.recycle();
//if it's not delayed for a while or the href attribute is not removed, then the above code would click into
// the anchor element instead of select it's text.
/* restore href attribute */
mWebView.postDelayed(() -> mWebView.evaluateJavascript("restoreTouchtarget()", null), 100);
}
});
}
return true;
In my case, I've extended the WebView as WebViewmy to record last touched positions, lastX and lastY, in the onTouchEvent method.
Unfortunately, a clear, official way to do this is not available. Although, there are two APIs (selectText and copySelection) which are pending API council approval, that may help to do this, but they are not available at the moment.

if any email is set in textview then open the default email client if clicked

In my app if any number is set then on clicking it starts a call on that number, and if any website link is given then also it shows that underline and on clicking that it opens the browser.
Similarly, I want to open the email client if any email address is set in the textview and show it underline.
Here you will get about patterns.
Initially when the screen starts you need to check for the type of value and then set the styles and click functions for your TextView like below. I guess you know about how to send emails, make calls and open a web browser with a link. I have made three click listeners but using one is good. You can have a flags for that and depending on that you can make operations instead.
public void setStyleAndFunction(CharSequence target) {
if(Patterns.EMAIL_ADDRESS.matcher(target).matches()) {
textview.setonClickListener() {
// send email
}
}
if(Patterns.PHONE.matcher(target).matches()) {
textview.setonClickListener() {
// make call
}
}
if(Patterns.WEB_URL.matcher(target).matches()) {
//set style (underline)
textview.setonClickListener() {
//open a web browser
}
}
}
Try It works for me :
Just write this code TextView ClickEvent or set as Linkify and call this.
Intent i2 = new Intent(android.content.Intent.ACTION_SEND);
i2.setType("text/html");
i2.putExtra(Intent.EXTRA_CC,new String[]{"Your CC Mail ID"});
i2.putExtra(Intent.EXTRA_EMAIL , new String[]{"Your TO Mail ID"});
i2.putExtra(android.content.Intent.EXTRA_SUBJECT, "Your Mail Body");

How to establish communication between webview and html page in worklight?

I'm working on making a browser as a hybrid app using worklight framework for Android. I implemented my address bar as an input element which received the user input and pass the arguments to the webview to load the page.
However, I cannot figure out how to do the reverse: whenever the user click on a link in webview, I want the address bar to change to the new location.
Are you implementing a native page that is opened? If so, take a look at ChildBrowser, that basically does the same thing. It has a TextView being used as an address bar. You may decide to use it, or get the bits and pieces you want out of it. Regardless, I would image what you want to do something like this. By overriding the onLoadResource in the WebViewClient, you should be able to grab the url and change your TextBox.
In response to the comment below: inside your environment's main js file in the wlEnvInit() function:
function wlEnvInit(){
wlCommonInit();
// Environment initialization code goes here
document.onclick=manageLinks;
}
Then in this function get the url and set the text of your input element:
function manageLinks(event) {
var link = event.target;
//go up the family tree until we find the A tag
while (link && link.tagName != 'A') {
link = link.parentNode;
}
if (link) {
var url = link.href;
console.log("url = " + url);
//You can decide if you want to separate external or
//internal links, depending on your application
var linkIsExternal = ((url.indexOf('http://') == 0) || (url.indexOf('https://') == 0));
if (linkIsExternal) {
myInput.setText(url);
return false;
}
}
return true;
}
Inside of your WebView, inside the plugin, intercept the URL like this:
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
//use this area to set your input. Depending on how you
//implemented your plugin, you may need to return this value
//back to your main activity
Toast.makeText(cordova.getActivity(), "Loading: " + url, Toast.LENGTH_LONG).show();
}
});
Have you try to get the url from the href of and assign to the input variable and do the get/post? I know that it is possible in SDK i figure it dont will be harder in a framework. You can store the hiperlinks in a array with a parser or something similar.
example pseudocode:
When_hiperlink_clicked: //could be like a listener (search about it)
url = hiperlink.getURL("myHiperlink");
myinput.setText(url);
execute_input_bar_action();
Is difficult to figure out without code or something more, sorry.

Categories

Resources