Android WebView link color - android

I am using WebView to show websites inside my application, and I was wondering is it possible to change link color and style which is by default blue and underlined?
I searched about it but there are all questions and solutions about removing the highlight around the link, nothing about the link itself. I just want to know is there some solution as easy as TextView's android:textColorLink or will I need to alter the website body somehow?
Thanks!

Okay, I managed to do it and wanted to share my way for the future visitors.
First I created a css file with the desired style, named style.css, saved under assets folder
a {color:purple; text-decoration:none}
Then, in the code I loaded the page as follows where content is the actual html content of the page
String htmlBody = "<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" />" + content;
mWebView.loadDataWithBaseURL("file:///android_asset/", htmlBody, "text/html", "utf-8",
null);
That's it! Hope it helps somebody.

Here is an example of how to add html links and customize them:
WebSettings webViewSettings = webView.getSettings();
webViewSettings.setDefaultFontSize(AppSettings.defaultFontSize);
webView.setBackgroundColor(Color.TRANSPARENT);
webView.loadDataWithBaseURL("file:///android_asset", Util.replaceLinkTags(myText), "text/html", "utf-8", null);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("file")) {
Intent intent = new Intent(MyActivity.this, MyActivity.class);
intent.putExtra("word", Uri.parse(url).getLastPathSegment());
startActivity(intent);
return true;
} else
return false;
}
});
public static String replaceLinkTags(String text) {
text = "<html><head>"
+ "<style type=\"text/css\">body{color:" + "#424242" + ";} a{color:#00B8D4; text-decoration:none; font-weight:bold;}"
+ "</style></head>"
+ "<body>" + text + "</body></html>";
String str;
while ((text.indexOf("\u0082") > 0)) {
if ((text.indexOf("\u0082") > 0) && (text.indexOf("\u0083") > 0)) {
str = text.substring(text.indexOf("\u0082") + 1, text.indexOf("\u0083"));
text = text.replaceAll("\u0082" + str + "\u0083", "" + str + "");
}
}
return text;
}

Related

How can I load video into an app from backend?

My problem is how to a show video from the admin backend into my android app. When I and adding the iframe from TinyMCE Editor, it looks like this:
But in my android app I get this:
I cannot understand what exactly is happening and I'm sharing you a section of my code of what I'm doing in the fragment.
if (item.getContent().length() != 0) {
mWebView.setVisibility(View.VISIBLE);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setMinimumFontSize(14);
String htmlContent = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
+ "<head>"
+ "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />"
+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"/>"
+ "<style type=\"text/css\">body{color: #525252;} img {max-width: 100%; height: auto}</style>"
+ "</head>"
+ item.getContent()
+ "";
mWebView.loadData(htmlContent, "text/html; charset=utf-8", "UTF-8");
} else {
mWebView.setVisibility(View.GONE);
}
if (item.getImgUrl().length() > 0) {
imageLoader.get(item.getImgUrl(), ImageLoader.getImageListener(mItemImg, R.drawable.img_loading, R.drawable.img_loading));
mItemImg.setVisibility(View.VISIBLE);
mItemImgSeparatorLine.setVisibility(View.VISIBLE);
} else {
mItemImg.setVisibility(View.GONE);
mItemImgSeparatorLine.setVisibility(View.GONE);
}
mPostTopSeparatorLine.setVisibility(View.GONE);
mPostMessage.setVisibility(View.GONE);
if (item.getAllowComments() == 0 && App.getInstance().getId() != 0) {
mPostTopSeparatorLine.setVisibility(View.VISIBLE);
mPostMessage.setVisibility(View.VISIBLE);
mPostMessage.setText(getString(R.string.msg_comments_disabled));
}
if (App.getInstance().getId() == 0) {
mPostTopSeparatorLine.setVisibility(View.VISIBLE);
mPostMessage.setVisibility(View.VISIBLE);
mPostMessage.setText(getString(R.string.msg_auth_prompt_comment));
}
}
For my Android App I'm working with a WebView as you can see in the above code. Do you have any idea why is it not working as expected? Thanks for your help.
You are trying to load an iFrame in WebView. To do so, use first create a string with the HTML.
String html = "<iframe width=\"560\" height=\"315\" src=\"your_src\" frameborder=\"0\" allowfullscreen></iframe>";
Now call loadData.
mWebview.loadData(html, "text/html", null);

How to load correctly a string from asset html file in a webview

I have an html file in asset folder and i would like to load it in a webview. I would like to use the string, and not the file in order to replace the content of file when i want (keep only one file and change the content i want to display).
For example my html file is like this:
<!DOCTYPE html>
<html>
<head>
<title>This is demo</title>
</head>
<body>
<p data-height="265" data-theme-id="0" data-slug-hash="dYPxYp" data-default-tab="html,result" data-user="sckarolos" data-embed-version="2" data-pen-title="SVG Shape Example" class="codepen">
See the Pen SVG Shape Example
by sckarolos (#sckarolos) on CodePen.</p>
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script>
</body>
</html>
I have these two methods for reading the html file from assets as string and load it in a webview:
private String getHtmlFromAsset() {
InputStream is;
StringBuilder builder = new StringBuilder();
String htmlString = null;
try {
is = getAssets().open(htmlFilename);
if (is != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
htmlString = builder.toString();
}
} catch (IOException e) {
e.printStackTrace();
}
return htmlString;
}
/**
* Loads html page with the content.
*/
private void loadHtmlPage(WebView webView) {
String htmlString = getHtmlFromAsset();
if (htmlString != null) {
webView.loadDataWithBaseURL(null, htmlString, "text/html", "UTF-8", null);
}
else
Toast.makeText(this, "No such page", Toast.LENGTH_LONG).show();
}
And in my activity i use webview like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
AssetManager assetManager = getAssets();
//try to display html content
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAllowContentAccess(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setAllowFileAccessFromFileURLs(true);
webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
loadHtmlPage(webView);
}
On debuging i can see that my file read successfully and my string has the content of html file. But when i am trying load it in webview, the result is nothing. If i try to load the local html file using this:
webView.loadUrl("file:///android_asset/myFile.html");
then the file loads and displays successfully.
I suppose that my fault is in the way i use the string that i take back from getHtmlFromAsset and pass in loadHtmlPage.
Any help will be appreciated.
Here, code pan required javascript access so when link load you need to provide javascript access. this is working code also check into my emulator. Also, don't forget to give internet permission on the manifest.
XML:
<WebView
android:id="#+id/wv"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
JAVA:
String str = "<!DOCTYPE html>\n" +
"<html>\n" +
"<head>\n" +
" <title>This is demo</title>\n" +
"</head>\n" +
"<body>\n" +
"\n" +
"<p data-height=\"265\" data-theme-id=\"0\" data-slug-hash=\"dYPxYp\" data-default-tab=\"html,result\" data-user=\"sckarolos\" data-embed-version=\"2\" data-pen-title=\"SVG Shape Example\" class=\"codepen\">\n" +
" See the Pen SVG Shape Example\n" +
" by sckarolos (#sckarolos) on CodePen.</p>\n" +
"<script async src=\"https://production-assets.codepen.io/assets/embed/ei.js\"></script>\n" +
"\n" +
"\n" +
"</body>\n" +
"</html>";
WebView wv = findViewById(R.id.wv);
wv.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url){
// do your handling codes here, which url is the requested url
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl(url);
return false; // then it is not handled by default action
}
});
wv.loadData(str, "text/html", "UTF-8");

Get HTML Code from WebSite and remove unnecessary Code - Only display the Table in WebView

I am trying to get my app to sync itself with a website, and display only the table of a website. Example: Normal HTML framework, and the table is inside a div#table, so I did it pretty simple and built the HTML Framework:
String html = "<html> " +
"<head>" +
"</head>" +
"<body style=\"background-color: transparent\">" +
"?body" +
"</body>" +
"</html>";
And then I tried to replace the ?body with the table, but here's my problem: I have no clue how to do that and then load it into a transparent WebView. I found a little bit code online, and tried to get it working for my case, so here's that:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<String> links = new ArrayList();
setContentView(SliderCreator.createSlider(R.layout.activity_news, this));
wv = (WebView) findViewById(R.id.newsWebView);
wv.setBackgroundColor(Color.TRANSPARENT);
try {
String finalHTML = getIntent().getStringExtra("html");
if (!finalHTML.contains("<html>")) {
String css = "";
for(String link : links) {
css+=Utils.getHTML(link);
}
finalHTML = html.replace("?body", getIntent().getStringExtra("html")).replace("?css", css);
}
wv.getSettings().setJavaScriptEnabled(true);
//open URLs in external Browser
wv.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
});
wv.loadDataWithBaseURL("", finalHTML, "text/html", "UTF-8", "");
} catch(Exception e) {
Toast.makeText(this, "An error occured...", Toast.LENGTH_LONG).show();
}
But that doesn't work.. Can somebody help me out get that working for me?
(Btw.: I tried it with RegEx, didn't work, I tried it with JSoup, didn't work either...)
try using HTML Agility Pack if not working with RegEx
Please note, your RegEx might not work the desired way if the text contains nested table tags

How to display some part of webpage in android webview?

I am using an android WebView and I want to load webpage on my android device but display only some parts of webpage, not the whole page.
Is this possible?
I think what you want to do is remove some content from your HTML page and then display it in the WebView. This is possible via javascript so just before you display the page add some javascript code that will remove the elements you don't want.
LIKE
final WebView mWebView = (WebView) findViewById(R.id.mWebViewId);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
mWebView.loadUrl("javascript:(function() { " +
"document.getElementById('tableid')[0].style.display='none'; " +
"})()");
}
});
mWebView.loadUrl(youUrl);
Just replace document.getElementsByTagName('tableid') with document.getElementsByTagName('theElementYouWantToRemove') for every element and you're set. Original solution can be found at Display a part of the webpage on the webview android
for those who still looking for a solution:
WebView webView = findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
mWebView.loadUrl("javascript:(function() { " +
"document.getElementsByClassName('className1')[0].remove();
document.getElementsByClassName('className2')[0].remove();
document.getElementsByClassName('className3')[0].remove();" +
"})()");
}
});
webView.loadUrl(url);
In Kotlin in this way:
view.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView, url: String) {
view.loadUrl(
"javascript:(function() { " +
"var head = document.getElementsByClassName('header')[0].style.display='true'; " +
"var head = document.getElementsByClassName('art-bnr')[0].style.display='none'; " +
"var head = document.getElementsByClassName('container-box')[0].style.display='none'; " +
"var head = document.getElementsByClassName('blog-sidebar')[0].style.display='none'; " +
"var head = document.getElementsByClassName('footer-container')[0].style.display='none'; " +
"})()"
) } }
view.loadUrl(url)

how to display a site into android webview without footer and header

i need to display another website into my android webview without it's header and footer
wb.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
wb.loadUrl("javascript:(function() { " +"document.getElementsByTagName('header')[0].style.display=\"none\"; " + "})()");
}
});
wb.loadUrl(url);
setContentView(wb);
Why not use iframe?
Try something like this -
String iframe = "<iframe scrolling=\"no\" src=\"YOUR URL\"" +
"width=\"400px\" height=\"300\"></iframe>";
webview.getSettings().setJavaScriptEnabled(true); //be sure to enable this or
//page might not load properly
webview.loadDataWithBaseURL("", iframe, "text/html", "UTF-8", "");
//loading iframe
You can customize the iframe code according to your needs. Be sure to add \ before every " in your HTML Code.

Categories

Resources